一、概述
SQL
语句实现数据的并集(union
)、交集(intersect
)、差集(except
)。
二、案例
1、stu表
id | name |
---|---|
1 | 张三 |
2 | 李四 |
3 | 王二 |
2、并集 union
union
运算:表示取并集,例如:
select * from stu where id <= '2'
UNION
select * from stu where id >= '2'
id | name |
---|---|
1 | 张三 |
2 | 李四 |
3 | 王二 |
union
会自动去除重复数据,如果需要显示重复的可以使用 union all
。
select * from stu where id <= '2'
UNION ALL
select * from stu where id >= '2'
id | name |
---|---|
1 | 张三 |
2 | 李四 |
2 | 李四 |
3 | 王二 |
3、交集 intersect
intersect
运算:表示取交集,例如:
select * from stu where id <= '2'
INTERSECT
select * from stu where id >= '2'
id | name |
---|---|
2 | 李四 |
4、差集 except
except
运算:表示对两个相同结果集的关系去差集,例如:
select * from stu where id <= '2'
EXCEPT
select * from stu where id >= '2'
id | name |
---|---|
1 | 张三 |