Documentation Home

13.2.10.4 INTERSECT 子句

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)

UNIONand 一样EXCEPT,如果 未指定DISTINCTnor 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 在UNIONand 之前计算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 中添加。