秒懂-7种join


CREATE TABLE emp (
id int NOT NULL AUTO_INCREMENT,
name varchar(255) DEFAULT NULL,
dept_id int DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO emp VALUES (1, '小红', 1);
INSERT INTO emp VALUES (2, '小明', 2);
INSERT INTO emp VALUES (3, '老王', 100);

CREATE TABLE dept (
id int NOT NULL AUTO_INCREMENT,
name varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8;

INSERT INTO dept VALUES (1, '开发部');
INSERT INTO dept VALUES (2, '运营部');
INSERT INTO dept VALUES (3, '编辑部');
数据准备完毕

第一种

左右对应才有

select
*
FROM emp e
inner join dept d
on e.dept_id = d.id

第二种

左右全有

select * FROM emp left join dept on emp.dept_id = dept.id UNION select * FROM emp right join dept on emp.dept_id = dept.id

第三种

不解释

select * FROM emp left join dept on emp.dept_id = dept.id

第四种

不解释

select * FROM emp right join dept on emp.dept_id = dept.id

第五种

员工 部门为空的员工

select
*
FROM emp e
left join dept d
on e.dept_id = d.id
where d.id is NULL

第六种

没有员工的部门

select
*
FROM emp e
right join dept d
on e.dept_id = d.id
where e.id is NULL

第⑦种

语句不提供

还是贴吧

select
*
FROM emp e
left join dept d
on e.dept_id = d.id
where d.id is NULL
UNION
select
*
FROM emp e
right join dept d
on e.dept_id = d.id
where e.id is NULL

posted @ 2020-10-25 18:46  z_先生  阅读(248)  评论(0编辑  收藏  举报