测试必备的Mysql常用sql语句系列

https://www.cnblogs.com/poloyy/category/1683347.html

 

前言

  • 外连接分为两种:left join、right join
  • 外连接显示的内容要比内连接多,是对内连接的补充
  • left join的主表是左表,从表是右表
  • right join的主表是右表,从表是左表
  • 外连接会返回主表的所有数据,无论在从表是否有与之匹配的数据,若从表没有匹配的数据则默认为空值(NULL)
  • 外连接只返回从表匹配上的数据
  • 重点:在使用外连接时,要分清查询的结果,是需要显示左表的全部记录,还是右表的全部记录

 

left join、right join 的语法格式

SELECT <字段名> FROM <表1> LEFT OUTER JOIN <表2> <ON子句>
SELECT <字段名> FROM <表1> RIGHT OUTER JOIN <表2> <ON子句>

语法格式说明

  • outer可以省略,只写 left join 、 right join 
  • on是设置左连接的连接条件,不能省略

 

先看看dept、emp表有什么数据

dept表

emp表

 

left join 的栗子

SQL分析

  • 主表:emp
  • 从表:dept
  • 根据 emp 表的员工 dept_id 和 dept 表的部门 id 进行匹配
  • 因为 emp 是主表,所以最后两条记录的 dept_id 在 dept 表没有匹配到 id,但是仍然会查询出来,然后将右表的数据置为NULL
select * from emp as a left join dept as b on a.dept_id = b.id;

 

left join + where 的栗子

SQL分析

  • 主表:emp
  • 从表:dept
  • 若不看where,前面的查询结果和上面的栗子一样
  • where的作用:将上面的查询结果集进行过滤,最终只返回 id 是 NULL的记录
select * from emp as a left join dept as b on a.dept_id = b.id where b.id is null;

知识点

  • 如果外连接中有 where 关键字,on是为了关联两张表,而where是将外连接查询的结果集进行条件筛选
  • 所以执行顺序是:on  -》 join -》 where
  • on:筛选两张表可以进行连接数据
  • join:将筛选后的数据连接起来
  • where:将连接后的数据结果集再次条件筛选

 

right join 的栗子

select * from emp as a right join dept as b on a.dept_id = b.id;

SQL分析

  • 主表:dept
  • 从表:emp
  • 根据 dept 表的 id 和 emp 表的 dept_id 进行匹配
  • 因为 dept 是主表,所以最后两条记录的 id 在 emp 表没有匹配到 dept_id,但是仍然会查询出来,然后将左表的数据置为NULL