SQL FULL JOIN 组合了左右外部联接的输出,联接的表将包含两个表中的所有记录,并为任一侧缺少的匹配项填充NULL。
FULL JOIN - 语法
FULL JOIN 的基本语法如下-
SELECT table1.column1, table2.column2... FROM table1 FULL JOIN table2 ON table1.common_field=table2.common_field;
FULL JOIN - 示例
请考虑以下两个表。
表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 | +-----+---------------------+-------------+--------+
现在,让无涯教程使用FULL JOIN连接这两个表,如下所示。
SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS FULL JOIN ORDERS ON CUSTOMERS.ID=ORDERS.CUSTOMER_ID;
这将产生以下输出-
+------+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +------+----------+--------+---------------------+ | 1 | Ramesh | NULL | NULL | | 2 | Khilan | 1560 | 2019-11-20 00:00:00 | | 3 | kaushik | 3000 | 2019-10-08 00:00:00 | | 3 | kaushik | 1500 | 2019-10-08 00:00:00 | | 4 | Chaitali | 2060 | 2018-05-20 00:00:00 | | 5 | Hardik | NULL | NULL | | 6 | Komal | NULL | NULL | | 7 | Learnfk | NULL | NULL | | 3 | kaushik | 3000 | 2019-10-08 00:00:00 | | 3 | kaushik | 1500 | 2019-10-08 00:00:00 | | 2 | Khilan | 1560 | 2019-11-20 00:00:00 | | 4 | Chaitali | 2060 | 2018-05-20 00:00:00 | +------+----------+--------+---------------------+
如果您的数据库不支持FULL JOIN(MySQL不支持FULL JOIN),则可以使用 UNION ALL 子句来组合这两个JOINS,如下所示。
SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID=ORDERS.CUSTOMER_ID UNION ALL SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID=ORDERS.CUSTOMER_ID
参考链接
https://www.learnfk.com/sql/sql-full-joins.html
标签:00,FULL,JOIN,无涯,2019,NULL,ID From: https://blog.51cto.com/u_14033984/9285246