首先创建需要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
作者:九道门聊数据
链接:https://www.zhihu.com/question/486152274/answer/2300115455
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
最新评论: