SELECT ...
INTERSECT [ALL | DISTINCT] SELECT ...
[INTERSECT [ALL | DISTINCT] SELECT ...]
INTERSECT
将多个SELECT
语句的结果限制为所有公共的行。例子:
mysql> TABLE a;
+------+------+
| m | n |
+------+------+
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
+------+------+
3 rows in set (0.00 sec)
mysql> TABLE b;
+------+------+
| m | n |
+------+------+
| 1 | 2 |
| 1 | 3 |
| 3 | 4 |
+------+------+
3 rows in set (0.00 sec)
mysql> TABLE c;
+------+------+
| m | n |
+------+------+
| 1 | 3 |
| 1 | 3 |
| 3 | 4 |
+------+------+
3 rows in set (0.00 sec)
mysql> TABLE a INTERSECT TABLE b;
+------+------+
| m | n |
+------+------+
| 1 | 2 |
| 3 | 4 |
+------+------+
2 rows in set (0.00 sec)
mysql> TABLE a INTERSECT TABLE c;
+------+------+
| m | n |
+------+------+
| 3 | 4 |
+------+------+
1 row in set (0.00 sec)
与UNION
and
一样EXCEPT
,如果
未指定DISTINCT
nor ALL
,则默认为DISTINCT
.
DISTINCT
可以从交叉路口的任一侧删除重复项,如下所示:
mysql> TABLE c INTERSECT DISTINCT TABLE c;
+------+------+
| m | n |
+------+------+
| 1 | 3 |
| 3 | 4 |
+------+------+
2 rows in set (0.00 sec)
mysql> TABLE c INTERSECT ALL TABLE c;
+------+------+
| m | n |
+------+------+
| 1 | 3 |
| 1 | 3 |
| 3 | 4 |
+------+------+
3 rows in set (0.00 sec)
(TABLE c INTERSECT TABLE c
相当于刚刚显示的两个语句中的第一个。)
与UNION
一样,操作数必须具有相同的列数。结果集列类型也被确定为 for UNION
。
INTERSECT
的优先级高于 and 在UNION
and
之前计算EXCEPT
,因此此处显示的两个语句是等效的:
TABLE r EXCEPT TABLE s INTERSECT TABLE t;
TABLE r EXCEPT (TABLE s INTERSECT TABLE t);
对于INTERSECT ALL
,左侧表中任何唯一行的最大支持重复数是
4294967295
。
INTERSECT
在 MySQL 8.0.31 中添加。