我是靠谱客的博主 可爱裙子,这篇文章主要介绍MySQL系列(六)之多表查询,现在分享给大家,希望可以做个参考。

表数据准备

#建表
create table dep(
	id int,
	name varchar(20) 
);

create table emp(
	id int primary key auto_increment,
	name varchar(20),
	sex enum('male','female') not null default 'male',
	age int,
	dep_id int
);

#插入数据
insert into dep values
	(200,'技术'),
	(201,'人力资源'),
	(202,'销售'),
	(203,'运营');

insert into emp(name,sex,age,dep_id) values
	('steven','male',18,200),
	('sammi','female',48,201),
	('kevin','male',18,201),
	('nick','male',28,202),
	('owen','male',18,203),
	('jerry','female',18,204);

表查询

# inner join  内连接
# 只拼接两张表中公有的数据部分
select * from emp inner join dep on emp.dep_id = dep.id;
# where 写法默写是内联接(等同于inner join)
select * from emp,dep where emp.dep_id = dep.id;

# left join   左连接
# 左表所有的数据都展示出来 没有对应的项就用NULL
select * from emp left join dep on emp.dep_id = dep.id;

# right join  右连接
# 右表所有的数据都展示出来 没有对应的项就用NULL
select * from emp right join dep on emp.dep_id = dep.id;

# union		全连接  左右两表所有的数据都展示出来
select * from emp left join dep on emp.dep_id = dep.id
union
select * from emp right join dep on emp.dep_id = dep.id;

子查询

将一个查询语句的结果当做另外一个查询语句的条件去用

# 查询部门是技术或者人力资源的员工信息
1 先获取部门的id号
select id from dep where name='技术' or name = '人力资源';
2 再去员工表里面筛选出对应的员工
select name from emp where dep_id in (200,201);
3 最终结果
select * from emp where dep_id in (select id from dep where name='技术' or name = '人力资源');

最后

以上就是可爱裙子最近收集整理的关于MySQL系列(六)之多表查询的全部内容,更多相关MySQL系列(六)之多表查询内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(86)

评论列表共有 0 条评论

立即
投稿
返回
顶部