对于SQL的Join,在学习起来可能是比较乱的。我们知道,SQL的Join语法有很多inner的,有outer的,有left的,有时候,对于Select出来的结果集是什么样子有点不是很清楚。Coding Horror上有一篇文章(实在不清楚为什么Coding Horror也被墙)通过 文氏图 Venn diagrams解释了SQL的Join。
在这里呢我们先来建立两张有外键关联的张表。
CREATE DATABASE db0206;
USE db0206;
CREATE TABLE `db0206`.`tbl_dept`(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`deptName` VARCHAR(30),
`locAdd` VARCHAR(40),
PRIMARY KEY (`id`)
) ENGINE=INNODB CHARSET=utf8;
CREATE TABLE `db0206`.`tbl_emp`(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20),
`deptId` INT(11),
PRIMARY KEY (`id`),
FOREIGN KEY (`deptId`) REFERENCES `db0206`.`tb_dept`(`id`)
) ENGINE=INNODB CHARSET=utf8;
/*插入数据*/
INSERT INTO tbl_dept(deptName,locAdd) VALUES('RD',11);
INSERT INTO tbl_dept(deptName,locAdd) VALUES('HR',12);
INSERT INTO tbl_dept(deptName,locAdd) VALUES('MK',13);
INSERT INTO tbl_dept(deptName,locAdd) VALUES('MIS',14);
INSERT INTO tbl_dept(deptName,locAdd) VALUES('FD',15);
INSERT INTO tbl_emp(NAME,deptId) VALUES('z3',1);
INSERT INTO tbl_emp(NAME,deptId) VALUES('z4',1);
INSERT INTO tbl_emp(NAME,deptId) VALUES('z5',1);
INSERT INTO tbl_emp(NAME,deptId) VALUES('w5',2);
INSERT INTO tbl_emp(NAME,deptId) VALUES('w6',2);
INSERT INTO tbl_emp(NAME,deptId) VALUES('s7',3);
INSERT INTO tbl_emp(NAME,deptId) VALUES('s8',4);
select * from tbl_dept a left join tbl_emp b on a.id=b.deptId;
select * from tbl_dept a right join tbl_emp b on a.id=b.deptId;
elect * from tbl_dept a left join tbl_emp b on a.id=b.deptId where b.deptId is null;
select * from tbl_dept a right join tbl_emp b on a.id=b.deptId where a.id is null;
select * from tbl_dept a right join tbl_emp b on a.id=b.deptId
union
select * from tbl_dept a left join tbl_emp b on a.id=b.deptId;
select * from tbl_dept a right join tbl_emp b on a.id=b.deptId where a.id is null union select * from tbl_dept a left join tbl_emp b on a.id=b.deptId where b.deptId is null;
作 者:haifeiWu
原文链接:https://cloud.tencent.com/developer/article/1333331
版权声明:非特殊声明均为本站原创作品,转载时请注明作者和原文链接。