JOIN、CROSS JOIN、INNER JOIN
在 MySQL 中等價的,都是構成笛卡爾積。
select * from a,b
id name id aid name
1 b1 1 1 b1
2 a1 1 1 b1
1 b1 2 1 b2
2 a1 2 1 b2
1 b1 3 2 b3
2 a1 3 2 b3
1 b1 4 2 b4
2 a1 4 2 b4
複製程式碼
a [LEFT] JOIN b USING (c1, c2)
要求a表和b表中都必須存在USING中定義的c1, c2兩列,且兩列在兩個表中的值相同,否則報錯。
select * from a left join b using (id)
id name aid name
1 b1 1 b1
2 a1 1 b2
上面的語句等價於
select coalesce(a.id, b.id) as id, a.name, b.aid, b.name from a left join b on a.id = b.id
複製程式碼
NATURAL [LEFT] JOIN
等價於使用限制所有同名列都在USING子句中的 [LEFT] JOIN
重複的列不會重複顯示
select * from a natural join b
id name aid
1 b1 1
上面的語句等價於
select coalesce(a.id, b.id) as id, coalesce(a.name, b.name) as name, b.aid from a join b on a.id = b.id and a.name = b.name
複製程式碼
STRAIGHT_JOIN
類似於 JOIN, 只是左表在右表之前讀。
select * from a straight_join b;
<=>
select * from a join b;
複製程式碼
JOIN 比 ,
優先順序更高
t1, t2 join t3
等價於
t1, (t2 join t3)
複製程式碼
SELECT * FROM t1, t2 JOIN t3 ON (t1.i1 = t3.i3);
該語句會報Unknown column 't1.i1' in 'on clause'的錯
原因就是JOIN的優先順序高於 , 的,語句等價於:
SELECT * FROM t1, (t2 JOIN t3 ON (t1.i1 = t3.i3));
複製程式碼
案例資料表
CREATE TABLE `a` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
INSERT INTO `a` (`id`, `name`)
VALUES
(1, 'b1'),
(2, 'a1');
CREATE TABLE `b` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`aid` int(11) DEFAULT NULL,
`name` varchar(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
INSERT INTO `b` (`id`, `aid`, `name`)
VALUES
(1, 1, 'b1'),
(2, 1, 'b2'),
(3, 2, 'b3'),
(4, 2, 'b4');
複製程式碼