解释一下MySQL中内连接,外连接等的区别
下图展示了 LEFT JOIN、RIGHT JOIN、INNER JOIN、OUTER JOIN 相关的 7 种用法。
INNER JOIN(内连接)
在表中存在至少一个匹配时,INNER JOIN 关键字返回行(并集)。
注意:INNER JOIN 与 JOIN 是相同的。
SELECT <select_list>
FROM Table_A A
INNER JOIN Table_B B
ON A.Key = B.Key
LEFT JOIN(左连接)
LEFT JOIN 关键字会从左表 (table_name1) 那里返回所有的行,即使在右表 (table_name2) 中没有匹配的行。
注意:在某些数据库中, LEFT JOIN 称为 LEFT OUTER JOIN。
SELECT <select_list>
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
RIGHT JOIN(右连接)
RIGHT JOIN 关键字会右表 (table_name2) 那里返回所有的行,即使在左表 (table_name1) 中没有匹配的行。
注意:在某些数据库中, RIGHT JOIN 称为 RIGHT OUTER JOIN。
SELECT <select_list>
FROM Table_A A
RIGHT JOIN Table_B B
ON A.Key = B.Key
OUTER JOIN(外连接)
SELECT <select_list>
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.Key = B.Key
"Websites" 表的数据:
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 2 | 淘宝 | https://www.taobao.com/ | 13 | CN |
| 3 | 菜鸟教程 | http://www.runoob.com/ | 4689 | CN |
| 4 | 微博 | http://weibo.com/ | 20 | CN |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
| 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND |
+----+---------------+---------------------------+-------+---------+
"access_log" 网站访问记录表的数据:
+-----+---------+-------+------------+
| aid | site_id | count | date |
+-----+---------+-------+------------+
| 1 | 1 | 45 | 2016-05-10 |
| 2 | 3 | 100 | 2016-05-13 |
| 3 | 1 | 230 | 2016-05-14 |
| 4 | 2 | 10 | 2016-05-14 |
| 5 | 5 | 205 | 2016-05-14 |
| 6 | 4 | 13 | 2016-05-15 |
| 7 | 3 | 220 | 2016-05-15 |
| 8 | 5 | 545 | 2016-05-16 |
| 9 | 3 | 201 | 2016-05-17 |
+-----+---------+-------+------------+
MySQL中不支持 FULL OUTER JOIN,但是我们可以对左连接和右连接的结果做 UNION (UNION会剔除重复行,UNION ALL不会剔除重复行)操作来实现。
你可以在 SQL Server 测试以下实例。
SELECT Websites.name, access_log.count, access_log.date
FROM Websites
FULL OUTER JOIN access_log
ON Websites.id=access_log.site_id
ORDER BY access_log.count DESC;
注意:FULL OUTER JOIN 关键字返回左表(Websites)和右表(access_log)中所有的行。如果 "Websites" 表中的行在 "access_log" 中没有匹配或者 "access_log" 表中的行在 "Websites" 表中没有匹配,也会列出这些行。
LEFT JOIN EXCLUDING INNER JOIN(左连接-内连接)
SELECT <select_list>
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL
RIGHT JOIN EXCLUDING INNER JOIN(右连接-内连接)
SELECT <select_list>
FROM Table_A A
RIGHT JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL
OUTER JOIN EXCLUDING INNER JOIN(外连接-内连接)
MySQL不支持FULL OUTER JOIN,可以使用Union(排除掉重复的数据)或Union All替代。
SELECT <select_list>
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL OR B.Key IS NULL
交叉连接(笛卡尔积)
使用下列命令同时查询玩具表的toy列和男孩表的boy列,得到的结果就是交叉连接:
SELECT t.toy,b.boy
FROM toys AS t
CROSS JOIN
boys AS b;
其中CROSS JOIN可以省略
SELECT t.toy,b.boy
FROM toys AS t,boys AS b;
交叉连接会把第一张表的每个值与第二张表的每个值进行匹配,结果如下:
参考: |