在最新的 MySQL 版本 ( 8.0.31 ) 中,MySQL 添加了对 SQL 标准INTERSECT和EXCEPT表运算符的支持。让我们看看如何使用它们。
我们将使用下表:
CREATE TABLE `new` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`tacos` int DEFAULT NULL,
`sushis` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
对于我们的团队会议,我们将订购炸玉米饼和寿司。
每条记录代表每个团队成员的顺序:
select * from new;
+----+-------------+-------+--------+
| id | name | tacos | sushis |
+----+-------------+-------+--------+
| 1 | Kenny | NULL | 10 |
| 2 | Miguel | 5 | 0 |
| 3 | lefred | 4 | 5 |
| 4 | Kajiyamasan | NULL | 10 |
| 5 | Scott | 10 | NULL |
| 6 | Lenka | NULL | NULL |
+----+-------------+-------+--------+
Intersect
手册说,INTERSECT将多个SELECT语句的结果限制为所有人共有的那些行。INTERSECT 运算符是 ANSI/ISO SQL 标准_(ISO/IEC 9075-2:2016(E))的一部分。
我们要运行两个查询,第一个将列出团队成员选择 tacos 的所有记录,第二个将返回该人选择 sushi’s 的所有记录。
这两个单独的查询是:
(query 1) select * from new where tacos>0;
(query 2) select * from new where sushis>0;

两个结果中唯一出现的记录是id=3的记录。
让我们用它INTERSECT来确认:
select * from new where tacos > 0
intersect
select * from new where sushis > 0;
+----+--------+-------+--------+
| id | name | tacos | sushis |
+----+--------+-------+--------+
| 3 | lefred | 4 | 5 |
+----+--------+-------+--------+
太好了,在以前的 MySQL 版本上,这种查询的结果是:
ERROR 1064 (42000): You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near
'intersect select * from new where sushis > 0' at line 1
Except
在手册中,我们可以读到EXCEPT将第一条语句的结果限制SELECT为(也)在第二条语句中找不到的那些行。
让我们找出所有只吃炸玉米饼的团队成员EXCEPT:
select * from new where tacos > 0
except
select * from new where sushis > 0;
+----+--------+-------+--------+
| id | name | tacos | sushis |
+----+--------+-------+--------+
| 2 | Miguel | 5 | 0 |
| 5 | Scott | 10 | NULL |
+----+--------+-------+--------+

如果我们想要执行相反的操作并获得所有只吃寿司的人,我们将查询顺序颠倒如下:
select * from new where sushis > 0
except
select * from new where tacos > 0;
+----+-------------+-------+--------+
| id | name | tacos | sushis |
+----+-------------+-------+--------+
| 1 | Kenny | NULL | 10 |
| 4 | Kajiyamasan | NULL | 10 |
+----+-------------+-------+--------+
结论
MySQL 8.0.31 继承了 8.0 的传统,包括对 SQL 标准的支持,例如Window Functions、Common Table Expressions、Lateral Derived Tables、JSON_TABLES、JSON_VALUE ……一起享受 MySQL !
原文标题:Intersect and Except in MySQL 8.0
原文作者:LEFRED
原文地址:https://lefred.be/content/intersect-and-except-in-mysql-8-0/
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




