一淤毛、內(nèi)連接(INNER JOIN 或者 JOIN)
(1)語法:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
或者
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
(2)舉例:
SELECT Websites.name, access_log.count, access_log.date
FROM Websites
INNER JOIN access_log
ON Websites.id=access_log.site_id
ORDER BY access_log.count;
或者
SELECT Websites.name, access_log.count, access_log.date
FROM Websites
JOIN access_log
ON Websites.id=access_log.site_id
ORDER BY access_log.count;
(3)結(jié)果:
在這里插入圖片描述
(3)總結(jié):
內(nèi)聯(lián)接使用比較運算符根據(jù)每個表共有的列的值匹配兩個表中的行徒役。
二、外連接(OUTER JOIN)
1、左外連接(LEFT JOIN)
(1)語法:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
或者 LEFT 和 JION中間加入一個OUTER锈遥,與INNER類似。
(2) 舉例:
在websites.sql中加入一行數(shù)據(jù)7 stackoverflow hheoafhoaeghegho 0 IND(空格隔開,對應(yīng)插入篡撵,就是隨意的多插入了一個與另一張表的site_id對應(yīng)不上的id)
SELECT Websites.name, access_log.count, access_log.date
FROM Websites
LEFT JOIN access_log
ON Websites.id=access_log.site_id
ORDER BY access_log.count DESC;
(3)結(jié)果:
在這里插入圖片描述
(4)總結(jié):
根據(jù)條件Websites.id=access_log.site_id左表(Websites.sql)中有id為7而右表(Access_log.sql)中沒有site_id為7的匹配行也會顯示為null。LEFT JOIN從左表中返回所有行豆挽。
2育谬、右外連接(RIGHT OUTER JOIN)
(1)語法:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
或者 RIGHT 和 JION中間加入一個OUTER,與INNER類似帮哈。
(2)舉例:
SELECT Websites.name, access_log.count, access_log.date
FROM access_log
RIGHT JOIN Websites
ON access_log.site_id=Websites.id
ORDER BY access_log.count DESC;
或者 RIGHT 和 JION中間加入一個OUTER膛檀,與INNER類似。
(3)結(jié)果(結(jié)果和 上一個的結(jié)果一樣娘侍,因為上一個的左表就是這個的右表咖刃,仔細看SQL語句)
(4)總結(jié):
與左連接相反,右連接就是將右表(Websites.sql)的所有行返回私蕾。
3僵缺、全外連接(FULL OUTER JOIN)
(1)語法:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
(2)舉例:
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;
(3)結(jié)果:
MySQL中不支持FULL OUTER JOIN 可以通過左外連接和右外連接來實現(xiàn)。
SELECT
Websites.NAME,
access_log.count,
access_log.date
FROM
Websites
LEFT JOIN access_log ON Websites.id = access_log.site_id UNION
SELECT
Websites.NAME,
access_log.count,
access_log.date
FROM
Websites
RIGHT JOIN access_log ON Websites.id = access_log.site_id;
三踩叭、交叉連接(CROSS JOIN)
相當與笛卡爾積磕潮,左表和右表組合;