0
点赞
收藏
分享

微信扫一扫

MySQL学习10(外连接)

Ichjns 2022-03-13 阅读 53

#外连接

/*
  外连接
	
	应用场景:
	   用于查询一个表中有,而另一个表中没有的记录
		 
	特点:
    -外连接的查询结果为主表中的所有记录
		 如果从表中有和他匹配的,则显示匹配的值
		 如果从表中没有和它匹配的,则显示为null
		-左外连接,left join 左边是主表
     右外连接  right join 右边是主表
     左外和右外交换两表的顺序,可以实现同样的效果		 
	
*/
# 查询女神信息和对应的男神名
use girls;
select b1.*,b2.*
from beauty b1
left outer join boys b2
on b1.boyfriend_id = b2.id;

# 右连接
use girls;
select b1.*,b2.*
from beauty b1
right outer join boys b2
on b1.boyfriend_id = b2.id;

# 查询男朋友不在男生表的女神信息
select b1.*
from beauty b1
left outer join boys b2
on b1.boyfriend_id = b2.id
where boyName is null;

# 练习
# 1.查询编号>3的女神的男朋友信息,如果有则列出来,如果没有,用null填充
use girls;
select b1.*,b2.*
from beauty b1
left join boys b2
on b1.boyfriend_id = b2.id
where b1.id > 3;

# 2.查询哪个城市没有部门
use myemployees;
select city,department_name
from locations l
left join departments d
on l.location_id = d.location_id
where d.department_id is null;

# 3.查询部门名为SAL或IT的员工信息
select e.*,department_name
from employees e
left join departments d
on e.department_id = d.department_id
where department_name in('SAL','IT');

举报

相关推荐

0 条评论