MySQL的JOIN大家在日常工作中都用得很多,今天小朱老师就给大家整理了MySQL七种JOIN类型的用法,一起来深入了解一下吧。数据分析优质社群,等你加入哦~
首先创建需要JOIN的两个表:
CREATE TABLE `tbl_emp` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(30) DEFAULT NULL,
`deptID` VARCHAR(40) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `tbl_dept` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`deptName` VARCHAR(30) DEFAULT NULL,
`locAdd` VARCHAR(40) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
我们可以看到数据的呈现:
1、A ∩ B
SELECT *
FROM tbl_emp a
INNER JOIN tbl_dept b # 共有
ON a.deptID = b.ID
2、A ( = A ∩ B + A* )
SELECT *
FROM tbl_emp a
LEFT JOIN tbl_dept b
ON a.deptID = b.ID
3、B ( = A ∩ B + B* )
SELECT *
FROM tbl_emp a
RIGHT JOIN tbl_dept b
ON a.deptID = b.ID
4. A* ( = A - A ∩ B )
SELECT *
FROM tbl_emp a
LEFT JOIN tbl_dept b
ON a.deptID = b.ID # ON时主表保留
WHERE B.ID IS NULL # 筛选A表数据
5. B* ( = B - A ∩ B )
SELECT *
FROM tbl_emp a
RIGHT JOIN tbl_dept b
ON a.deptID = b.ID # ON时主表保留
WHERE a.deptID IS NULL # 筛选B表数据
6. A ∪ B
SELECT < select_list >
FROM TableA A
FULL OUTER JOIN TableB B ## FULL OUTER 仅oracle支持
ON A.Key = B.Key
-- MySQL格式
SELECT *
FROM tbl_emp a
LEFT JOIN tbl_dept b
ON a.deptID = b.ID
UNION
SELECT *
FROM tbl_emp a
RIGHT JOIN tbl_dept b
ON a.deptID = b.ID
7. A ∪ B - A ∩ B
SELECT < select_list >
FROM TableA A
FULL OUTER JOIN TableB B
ON A.Key = B.Key
WHERE A.Key IS NULL OR B.Key IS NULL
-- MySQL格式
SELECT *
FROM tbl_emp a
LEFT JOIN tbl_dept b
ON a.deptID = b.ID
UNION
SELECT *
FROM tbl_emp a
RIGHT JOIN tbl_dept b
ON a.deptID = b.ID
WHERE a.deptID IS NULL OR b.ID IS NULL
以上就是其中JOIN类型的介绍,大家可以用起来了哦。