MySQL 8.4 Release Notes
15.2.4 EXCEPT 子句
query_expression_body EXCEPT [ALL | DISTINCT] query_expression_body
[EXCEPT [ALL | DISTINCT] query_expression_body]
[...]
query_expression_body:
See Section 15.2.14, “Set Operations with UNION, INTERSECT, and EXCEPT”
EXCEPT
将第一个查询块的结果限制为第二个查询块中找不到的行。与UNION
和INTERSECT
一样,两个查询块都可以使用SELECT
、TABLE
或VALUES
。使用表a
、b
和c
(见第15.2.8节,“INTERSECT Clause”)的示例如下:
mysql> TABLE a EXCEPT TABLE b;
+------+------+
| m | n |
+------+------+
| 2 | 3 |
+------+------+
1 row in set (0.00 sec)
mysql> TABLE a EXCEPT TABLE c;
+------+------+
| m | n |
+------+------+
| 1 | 2 |
| 2 | 3 |
+------+------+
2 rows in set (0.00 sec)
mysql> TABLE b EXCEPT TABLE c;
+------+------+
| m | n |
+------+------+
| 1 | 2 |
+------+------+
1 row in set (0.00 sec)
与UNION
和INTERSECT
一样,如果不指定DISTINCT
或ALL
,默认为DISTINCT
。
DISTINCT
删除两个关系中找到的重复项,如下所示:
mysql> TABLE c EXCEPT DISTINCT TABLE a;
+------+------+
| m | n |
+------+------+
| 1 | 3 |
+------+------+
1 row in set (0.00 sec)
mysql> TABLE c EXCEPT ALL TABLE a;
+------+------+
| m | n |
+------+------+
| 1 | 3 |
| 1 | 3 |
+------+------+
2 rows in set (0.00 sec)
(第一个语句等同于TABLE c EXCEPT TABLE a
。)
与UNION
或INTERSECT
不同,EXCEPT
不是可交换的—that is,结果取决于操作数的顺序,如下所示:
mysql> TABLE a EXCEPT TABLE c;
+------+------+
| m | n |
+------+------+
| 1 | 2 |
| 2 | 3 |
+------+------+
2 rows in set (0.00 sec)
mysql> TABLE c EXCEPT TABLE a;
+------+------+
| m | n |
+------+------+
| 1 | 3 |
+------+------+
1 row in set (0.00 sec)
与UNION
一样,需要比较的结果集必须具有相同的列数。结果集列类型也像UNION
一样确定。