本教程解释了sql intersect
运算符,并向演示如何应用它来获取两个或多个查询的交集。
intersect
运算符是一个集合运算符,它从select语句返回两个或多个结果集的不同行。
假设有两个表记录:a(1,2)
和b(2,3)
。
下图说明了a
和b
表的交集。
紫色部分是绿色和蓝色结果集的交集。
与union运算符一样,intersect
运算符从最终结果集中删除重复的行。以下语句说明了如何使用intersect
运算符查找两个结果集的交集。
select
id
from
a
intersect
select
id
from
b;
要使用intersect
运算符,select
语句的列需要遵循以下规则:
select
语句中的列数及其顺序必须相同。以下select
语句返回表a
中的行:
select
id
from
a;
+----+
| id |
+----+
| 1 |
| 2 |
+----+
2 rows in set
以下语句从表b
中检索数据:
select
id
from
b;
+----+
| id |
+----+
| 2 |
| 3 |
+----+
2 rows in set
以下语句使用intersect
运算符来获取两个查询的交集。
select
id
from
a
intersect
select
id
from
b;
执行上面查询语句,得到以下结果:
sql intersect带有order by示例
要对intersect
运算符返回的结果集进行排序,请将order by
子句放在所有语句的末尾。
例如,以下语句将intersect
运算符应用于a
和b
表,并按降序对id
列的组合结果集进行排序。
select
id
from
a
intersect
select
id
from
b
order by id desc
执行上面查询语句,得到以下结果:
使用inner join子句模拟sql intersect运算符
大多数关系数据库系统支持intersect
运算符,如oracle数据库,microsoft sql server,postgresql等。但是,某些数据库系统(mysql)不提供intersect
运算符。
要模拟sql intersect运算符,可以使用inner join子句,如下所示:
select
a.id
from
a
inner join b on b.id = a.id
它返回a
表中与b
表中匹配行的行,这些行产生与intersect
运算符相同的结果。
现在您应该对sql intersect
运算符有一个很好的理解,并知道如何使用它来查找多个查询的交集。