Table of Contents
1. Comparison table and table
2. Use difference set to implement relational division operation
3. Seek equal subsets
4. Delete duplicate rows
Exercise
Most of them come from "SQL Advanced Textbook", just taking notes. Some of the codes in the exercises are original. " > Most of them come from "SQL Advanced Textbook", just taking notes. Some of the codes in the exercises are original.
Home Database Mysql Tutorial Set operations using SQL

Set operations using SQL

Jun 04, 2018 am 09:29 AM
Operation conduct gather

This article mainly introduces the use of SQL for set operations, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

1. Comparison table and table

drop table if exists tbl_a;create table tbl_a(
key1 varchar(10),
col_1 int4,
col_2 int4,
col_3 int4
);insert into tbl_a values('A', 2, 3, 4);
insert into tbl_a values('B', 0, 7, 9);
insert into tbl_a values('c', 5, 1, 6);
drop table if exists tbl_b;create table tbl_b(
key1 varchar(10),
col_1 int4,
col_2 int4,
col_3 int4
);
insert into tbl_b values('A', 2, 3, 4);
insert into tbl_b values('B', 0, 7, 9);
insert into tbl_b values('c', 5, 1, 6);-- ## 如果union a b 行数一致则两张表相等 select count(1) row_cnt  from ( select * 
           from tbl_A           union 
          select *            from tbl_b
        ) tmp
;
Copy after login


Directly find the difference between the two tables

(select * from tbl_a except
 select * from tbl_b) union all
 (select * from tbl_b  except
  select * from tbl_a);
Copy after login

2. Use difference set to implement relational division operation

Build a table

drop table if exists skills;create table skills(
skill varchar(10)
);insert into skills values('oracle');
insert into skills values('unix');insert into skills values('java');drop table if exists empskills;create table empskills(
emp varchar(10),
skill varchar(10)
);insert into empskills values('相田','oracle');
insert into empskills values('相田','unix');
insert into empskills values('相田','java');
insert into empskills values('相田','c#');
insert into empskills values('神奇','oracle');
insert into empskills values('神奇','unix');
insert into empskills values('神奇','java');
insert into empskills values('平井','oracle');
insert into empskills values('平井','unix');
insert into empskills values('平井','PHP');
insert into empskills values('平井','Perl');
insert into empskills values('平井','C++');
insert into empskills values('若田部','Perl');
insert into empskills values('度来','oracle');
Copy after login
--把除法变成减法select distinct emp  from empskills es1 where not exists
        (select skill from skills
         expect         select skill from empskills es2          where es1.emp = es2.emp);
Copy after login

3. Seek equal subsets

drop table if exists supparts;create table supparts(
sup varchar(10),
part varchar(10)
);insert into supparts values('A', '螺丝');
insert into supparts values('A', '螺母');
insert into supparts values('A', '管子');
insert into supparts values('B', '螺丝');
insert into supparts values('B', '管子');
insert into supparts values('C', '螺丝');
insert into supparts values('C', '螺母');
insert into supparts values('C', '管子');
insert into supparts values('D', '螺丝');
insert into supparts values('D', '管子');
insert into supparts values('E','保险丝');
insert into supparts values('E', '螺母');
insert into supparts values('E', '管子');
insert into supparts values('F','保险丝');
Copy after login

Ideas: Both suppliers deal in the same type of parts (simply connect according to the part column) The number of parts types from the two suppliers is the same (that is, there is a one-to-one mapping) (count limit)

select a.sup s1, b.sup s2  from supparts a, supparts b where a.sup < b.sup                       -- 生成供应商的全部组合 
   and a.part = b.part                     -- 条件1:经营同种类型的零件 
 group by a.sup, b.suphaving count(*) = (select count(1)         -- 条件2:经营的零件的数量种类相同 a = 中间数                     from supparts c                    where c.sup = a.sup)   and count(*) = (select count(1)         -- 条件2:经营的零件的数量种类相同 b = 中间数                     from supparts d                    where d.sup = b.sup)
;
Copy after login

4. Delete duplicate rows

drop table if exists products;create table products(
rowid int4,
name1 varchar(10),
price int4
);insert into products values(1,&#39;苹果&#39;,50);insert into products values(2,&#39;橘子&#39;,100);
insert into products values(3,&#39;橘子&#39;,100);insert into products values(4,&#39;橘子&#39;,100);
insert into products values(5,&#39;香蕉&#39;,80);-- 删除重行高效SQL语句(1):通过EXCEPT求补集delete from productswhere rowid  in (select rowid           -- 全部rowid                   from products 
                 except                 -- 减去                 select max(rowid)      -- 要留下的rowid                   from products                  group by name1, price
                  );-- 删除重行高效SQL语句(2):通过not indelete from products where rowid not in (select max(rowid)                      from products                     group by name1, price
                    );
Copy after login

Exercise

-- 改进中用union的比较select 
    case when count(1) = (select count(1) from tbl_A)          
    and count(1) = (select count(1)+1 from tbl_b)         
    then count(1) else &#39;不相等&#39; end row_cnt  from ( select * from tbl_A          union 
         select * from tbl_b
        ) tmp
;
Copy after login

Most of them come from "SQL Advanced Textbook", just taking notes. Some of the codes in the exercises are original.

The above is the detailed content of Set operations using SQL. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why is it difficult to implement collection-like functions in Go language? Why is it difficult to implement collection-like functions in Go language? Mar 24, 2024 am 11:57 AM

It is difficult to implement collection-like functions in the Go language, which is a problem that troubles many developers. Compared with other programming languages ​​such as Python or Java, the Go language does not have built-in collection types, such as set, map, etc., which brings some challenges to developers when implementing collection functions. First, let's take a look at why it is difficult to implement collection-like functionality directly in the Go language. In the Go language, the most commonly used data structures are slice and map. They can complete collection-like functions, but

How to optimize Java collection sorting performance How to optimize Java collection sorting performance Jun 30, 2023 am 10:43 AM

Java is a powerful programming language that is widely used in various types of software development. In Java development, scenarios that often involve sorting collections are involved. However, if performance optimization is not performed for collection sorting, the execution efficiency of the program may decrease. This article will explore how to optimize the performance of Java collection sorting. 1. Choose the appropriate collection class In Java, there are many collection classes that can be used for sorting, such as ArrayList, LinkedList, TreeSet, etc. Different collection classes are in

A Practical Guide to the Where Method in Laravel Collections A Practical Guide to the Where Method in Laravel Collections Mar 10, 2024 pm 04:36 PM

Practical Guide to Where Method in Laravel Collections During the development of the Laravel framework, collections are a very useful data structure that provide rich methods to manipulate data. Among them, the Where method is a commonly used filtering method that can filter elements in a collection based on specified conditions. This article will introduce the use of the Where method in Laravel collections and demonstrate its usage through specific code examples. 1. Basic usage of Where method

Common concurrent collections and thread safety issues in C# Common concurrent collections and thread safety issues in C# Oct 09, 2023 pm 10:49 PM

Common concurrent collections and thread safety issues in C# In C# programming, handling concurrent operations is a very common requirement. Thread safety issues arise when multiple threads access and modify the same data at the same time. In order to solve this problem, C# provides some concurrent collection and thread safety mechanisms. This article will introduce common concurrent collections in C# and how to deal with thread safety issues, and give specific code examples. Concurrent collection 1.1ConcurrentDictionaryConcurrentDictio

Oracle database operation skills: detailed explanation of subtraction operation Oracle database operation skills: detailed explanation of subtraction operation Mar 02, 2024 pm 06:15 PM

As a powerful relational database management system, Oracle database provides a wealth of computing operations to meet user needs. In daily database operations, subtraction operation is a common and important operation. It can help us realize the subtraction operation of data to obtain the results we need. This article will discuss in detail the techniques related to subtraction operations in Oracle database, and give specific code examples to help readers better understand and use this function. 1. Basic concepts of subtraction operations in Oracle data

Add all elements from one collection to another using the addAll() method of the HashSet class Add all elements from one collection to another using the addAll() method of the HashSet class Jul 24, 2023 am 08:58 AM

Use the addAll() method of the HashSet class to add all elements in a collection to another collection. HashSet is an implementation class in the Java collection framework. It inherits from AbstractSet and implements the Set interface. HashSet is an unordered set based on a hash table, which does not allow duplicate elements. It provides many commonly used methods to operate elements in the collection, one of which is the addAll() method. The function of the addAll() method is to add the specified

Analysis and solutions to PHP floating point operation problems Analysis and solutions to PHP floating point operation problems Feb 27, 2024 am 11:03 AM

PHP is a scripting language widely used in website development. Its powerful functions and flexibility make it the tool of choice for many developers. However, PHP also has some problems when dealing with floating point operations, especially when it comes to precision and accuracy. This article will analyze PHP floating point operation problems and propose some solutions. It will also provide specific code examples to help readers better understand and solve these problems. Problem Analysis In PHP, floating point numbers are a data type used to represent decimals.

Java Iterator vs. Iterable: A step into writing elegant code Java Iterator vs. Iterable: A step into writing elegant code Feb 19, 2024 pm 02:54 PM

Iterator interface The Iterator interface is an interface used to traverse collections. It provides several methods, including hasNext(), next() and remove(). The hasNext() method returns a Boolean value indicating whether there is a next element in the collection. The next() method returns the next element in the collection and removes it from the collection. The remove() method removes the current element from the collection. The following code example demonstrates how to use the Iterator interface to iterate over a collection: Listnames=Arrays.asList("John","Mary","Bob");Iterator

See all articles