mysql七种join

2021-02-05 15:06:47 浏览数 (1)

一、数据准备

代码语言:javascript复制
CREATE TABLE `t_dept` (
`id` INT(11) NOT NULL AUTO_INCREMENT, `deptName` VARCHAR(30) DEFAULT NULL, `address` VARCHAR(40) DEFAULT NULL, PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `t_emp` (
`id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(20) DEFAULT NULL, `age` INT(3) DEFAULT NULL, `deptId` INT(11) DEFAULT NULL, empno int not null, PRIMARY KEY (`id`), KEY `idx_dept_id` (`deptId`)
#CONSTRAINT `fk_dept_id` FOREIGN KEY (`deptId`) REFERENCES `t_dept` (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO t_dept(deptName,address) VALUES('华山','华山');
INSERT INTO t_dept(deptName,address) VALUES('丐帮','洛阳');
INSERT INTO t_dept(deptName,address) VALUES('峨眉','峨眉山');
INSERT INTO t_dept(deptName,address) VALUES('武当','武当山');
INSERT INTO t_dept(deptName,address) VALUES('明教','光明顶');
INSERT INTO t_dept(deptName,address) VALUES('少林','少林寺');
INSERT INTO t_emp(NAME,age,deptId,empno) VALUES('风清扬',90,1,100001);
INSERT INTO t_emp(NAME,age,deptId,empno) VALUES('岳不群',50,1,100002);
INSERT INTO t_emp(NAME,age,deptId,empno) VALUES('令狐冲',24,1,100003);
INSERT INTO t_emp(NAME,age,deptId,empno) VALUES('洪七公',70,2,100004);
INSERT INTO t_emp(NAME,age,deptId,empno) VALUES('乔峰',35,2,100005);
INSERT INTO t_emp(NAME,age,deptId,empno) VALUES('灭绝师太',70,3,100006);
INSERT INTO t_emp(NAME,age,deptId,empno) VALUES('周芷若',20,3,100007);
INSERT INTO t_emp(NAME,age,deptId,empno) VALUES('张三丰',100,4,100008);
INSERT INTO t_emp(NAME,age,deptId,empno) VALUES('张无忌',25,5,100009);
INSERT INTO t_emp(NAME,age,deptId,empno) VALUES('韦小宝',18,null,100010);

二、t_emp表全部数据

三、t_dept全部数据

四、左连接 (A独有 AB独有) LEFT JOIN

代码语言:javascript复制
select * FROM t_emp left join t_dept ON t_emp.deptId = t_dept.id 

五、右连接 (B独有 AB独有) RIGHT JOIN

代码语言:javascript复制
select * FROM t_emp right join t_dept ON t_emp.deptId = t_dept.id 

六、内连接 (AB独有) Inner join

代码语言:javascript复制
select * FROM t_emp inner join t_dept ON t_emp.deptId = t_dept.id 

七、A独有

代码语言:javascript复制
select * FROM t_emp left  join t_dept ON t_emp.deptId = t_dept.id WHERE  t_dept.id  is null

八、B独有

代码语言:javascript复制
select * FROM t_emp right  join t_dept ON t_emp.deptId = t_dept.id WHERE  t_emp.id  is null

九、全连接 (A B) full join

代码语言:javascript复制
select * FROM t_emp left  join t_dept ON t_emp.deptId = t_dept.id 
union
select * FROM t_emp right join t_dept ON t_emp.deptId = t_dept.id 

十、A独有 B独有

代码语言:javascript复制
select * FROM t_emp left  join t_dept ON t_emp.deptId = t_dept.id WHERE  t_dept.id is null
union
select * FROM t_emp right join t_dept ON t_emp.deptId = t_dept.id  WHERE  t_emp.id is null

0 人点赞