對於inner join, outer join , left join , right join還是很模糊嗎?
沒關係,這邊提供最簡易的SQL版本,
輕鬆好上手。
首先,我們先建立2個資料表,分別是table1跟table2。
table1
沒關係,這邊提供最簡易的SQL版本,
輕鬆好上手。
首先,我們先建立2個資料表,分別是table1跟table2。
table1
id |
210 |
211 |
212 |
213 |
CREATE TABLE `table1` (
`id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `table1` (`id`) VALUES
(210),
(211),
(212),
(213);
-- 2016-02-09 23:16:25
`id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `table1` (`id`) VALUES
(210),
(211),
(212),
(213);
-- 2016-02-09 23:16:25
table2
id |
210 |
214 |
215 |
212 |
212 |
CREATE TABLE `table2` (
`id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
#台灣金站
INSERT INTO `table2` (`id`) VALUES
(210),
(214),
(215),
(212),
(212);
-- 2016-02-09 23:17:01
`id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
#台灣金站
INSERT INTO `table2` (`id`) VALUES
(210),
(214),
(215),
(212),
(212);
-- 2016-02-09 23:17:01
接下來就來測試inner join囉!!
Syntax
SELECT a.id, b.id
FROM table1 as a
INNER JOIN table2 as b
ON a.id= b.id
FROM table1 as a
INNER JOIN table2 as b
ON a.id= b.id
看看得到的結果:
id | id |
210 | 210 |
212 | 212 |
212 | 212 |
接下來換LEFT JOIN囉!
Syntax
SELECT a.id, b.id
FROM table1 as a
LEFT JOIN table2 as b
ON a.id= b.id
FROM table1 as a
LEFT JOIN table2 as b
ON a.id= b.id
看看得到的結果:
a.id | b.id |
210 | 210 |
211 | null |
212 | 212 |
212 | 212 |
213 | null |
結果說明:
Left join是以A表的記錄為基礎的,A可以看成左表,B可以看成右表,left join是以左表為準的.
換句話說,左表(A)的記錄將會全部表示出來,而右表(B)只會顯示符合搜索條件的記錄(例子中為: A.aID = B.bID).
B表記錄不足的地方均為NULL.
那麼RIGHT JOIN會是如何呢?
Syntax
SELECT a.id, b.id
FROM table1 as a
RIGHT JOIN table2 as b
ON a.id= b.id
FROM table1 as a
RIGHT JOIN table2 as b
ON a.id= b.id
看看得到的結果:
a.id | b.id |
210 | 210 |
null | 214 |
null | 215 |
212 | 212 |
212 | 212 |
哇,可以看到跟LEFT的情況倒過來了呢。
另外,很多人都不知道JOIN裡面USING 跟 ON 的差異在哪裡?
以我們剛剛第一個例子來說:
#範例 B-1
SELECT a.id, b.id
FROM table1 as a
INNER JOIN table2 as b
ON a.id= b.id
由於我們的欄位都是共同為ID這個名稱(two tables share a column of the exact same name ),SELECT a.id, b.id
FROM table1 as a
INNER JOIN table2 as b
ON a.id= b.id
所以其實也可以寫成這樣喔:
#範例 B-2
SELECT a.id, b.id
FROM table1 as a
INNER JOIN table2 as b
USING (id)
範例 B-1跟範例 B-2 執行結果都會得到一樣。SELECT a.id, b.id
FROM table1 as a
INNER JOIN table2 as b
USING (id)