Mysql只提供了并集(union),没有提供差集,和交集,可以用union来实现交和差.
先建两个结构一样的表table1和table2
create table table1(name varchar(20));
create table table2(name varchar(20));
插入数据
#向table1中插入数据
insert into table1 (name) values
('甲'),('乙'),('丙');
#向table1中插入数据
insert into table2 (name) values
('甲'),('乙'),('丁'),('戊'),('己');
一个简单的并集运算(默认去除重复条目,若不去除重复条目在'union'后面加上' all'):
select * from table1 union select * from table2;
结果如下
+------+
| name |
+------+
| 甲 |
| 乙 |
| 丙 |
| 丁 |
| 戊 |
| 己 |
+------+
用union来实现交:
table1与table2交集(原理就是求table1与table2不去除重复条目的并集,然后按名字分组,取其中重复条目)
select * from (select * from table1 union all select * from table2)temp group by name having count(*)>1;
结果如下
+------+
| name |
+------+
| 甲 |
| 乙 |
+------+
用union来实现差:
table1与table2差(取其中不重复条目)
select * from (select * from table1 union all select * from table2)temp group by name having count(*)=1;
结果如下
+------+
| name |
+------+
| 丙 |
| 丁 |
| 己 |
| 戊 |
+------+