SQL INTERSECT 子句用于组合两个SELECT语句,但仅返回第一个SELECT语句中与第二个SELECT语句中的行相同的行。这意味着INTERSECT仅返回两个SELECT语句返回的公共行,MySQL不支持INTERSECT运算符。
INTERSECT - 语法
INTERSECT 的基本语法如下。
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] INTERSECT SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]
INTERSECT - 示例
请考虑以下两个表。
表1 -客户表(CUSTOMERS)如下
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Learnfk | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+
表2 -订单表(ORDERS)如下。
+-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2019-10-08 00:00:00 | 3 | 3000 | | 100 | 2019-10-08 00:00:00 | 3 | 1500 | | 101 | 2019-11-20 00:00:00 | 2 | 1560 | | 103 | 2018-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+
现在,让无涯教程按如下所示将这两个表连接到SELECT语句中。
SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID=ORDERS.CUSTOMER_ID INTERSECT SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID=ORDERS.CUSTOMER_ID;
这将产生以下输出。
+------+---------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +------+---------+--------+---------------------+ | 3 | kaushik | 3000 | 2019-10-08 00:00:00 | | 3 | kaushik | 1500 | 2019-10-08 00:00:00 | | 2 | Ramesh | 1560 | 2019-11-20 00:00:00 | | 4 | kaushik | 2060 | 2018-05-20 00:00:00 | +------+---------+--------+---------------------+
参考链接
https://www.learnfk.com/sql/sql-intersect-clause.html
标签:00,Clause,无涯,ORDERS,2019,INTERSECT,ID,SELECT From: https://blog.51cto.com/u_14033984/9289031