DQL语句(三)------- 多表查询

发布时间 2023-05-17 16:21:31作者: 、怪咖

9、多表查询

9.1 多表连接

  • select * from emp,dept; -- 直接两张表之间加逗号就会全连接

  • 如果没有任何条件去连接两张表,那么会产生一张很大的表,两张表记录相乘条记录

  • 设置条件用点 . 比如:emp.deptno=dept.deptno(员工表中deptno=部门表中的deptno)

  • 自然连接(natural join)

    • select * from emp natural join dept
      
  • using(等值)

    • select * from emp join dept using(deptno) where sal>2000
      
  • on(可以不等值也可以等值)

    • select * from emp join dept on(emp.deptno=dept.deptno) where sal>2000
      

9.2 左右外连接

  • 左连接(left)

    • select * from emp left join dept using(deptno)
      
    • 显示语句左边表中所有数据(包括不符合要求的)

  • 右连接(right)

    • select * from emp right join dept using(deptno)
      
    • 显示语句右边表中所有数据

9.3 union与全外连接

  • union

    • 把几次查询的结果放在一起

    • select ename,sal,deptno from emp where deptno=10 and ename like '%A%'
      union
      select ename,sal,deptno from emp where deptno=20 and sal>1000
      union
      select ename,sal,deptno from emp where deptno=30 and sal<2000
      
    • union在全部查询出来的数据中重复的数据会自动去重(不会有重复的数据)

    • 如果不想去重,可以写成union all

    • select ename,sal,deptno from emp where ename like '%A%'
      union all
      select ename,sal,deptno from emp where deptno=20 and sal>1000
      union all
      select ename,sal,deptno from emp where deptno=30 and sal<2000
      
    • union all的效率更高于union

  • 全外连接

    • 左连接union右连接

    • select * from emp left join dept using(deptno)
      union
      select * from emp right join dept using(deptno)
      

9.4 自连接

  • 我们要查询的两个字段同时处于一张表上,我们只能将一张表当作含义不同的两张表去处理

  • 给同一张表取不同的别名(建议按所代表的含义去取名)

  • -- 查询每个员工与其直属上司的名字
    select e.ename,m.ename from emp e,emp m where e.mgr=m.empno;
    select e.ename,m.ename from emp e join emp m on(e.mgr=m.empno);
    

9.5 子连接

  • 把一个sql语句的查询结果当作另外一个sql语句的查询条件

  • -- 查询公司中薪资最低的员工姓名
    select ename,sal from emp where sal=(select min(sal) from emp);
    

9.6 伪表查询

  • 当查询语句中需要用到别的sql语句时,如果有多个条件就要用到伪表(也就是说类似于在一张表后面加两列,只是在这条语句中加两列)

  • -- 查询高于自己部门内平均薪资的员工信息
    select e.ename,e.sal,e.deptno,d.avgsal from emp e,(select deptno,avg(sal) avgsal from emp group by deptno) d where e.deptno = d.deptno and e.sal > d.avgsal;
    

更多关于DQL查询语句参考上面两篇博客DQL(一)DQL(二)