多表查询

多表查询

  查询语法:

    select * from emp,dept;   --会出现笛卡尔积

  多表查询分类:

    1.内连接查询

      隐式内连接查询:(使用)外键是空就会导致查询不了所有的数据

select * from emp,dept where emp.dept_id=dept.id

-- 正确的写法(用别名替换表,还有需要哪些字段查询哪些字段)
select
  t1.name,t1.gender,t2.name,t2.id
from
  emp t1,dept t2   -- 给表起别名
where
  emp.dept_id=dept.id

      显示的内连接查询

        语法:select 字段列表 from table_name inner join table_name1 on table_name.字段=table_name1.字段 

                  select * from emp inner join dept on emp.dept_id=dept.id;

    注意事项:从哪些表中查询,条件什么(内连接的条件),查询哪些字段

    2.外连接查询

      左外连接:查询的是左表所有数据,以及其交集部分。

        语法:select 字段列表 from 表1 left [outer] join 表2 on 条件    

                    select * from emp t1 left  join dept t2 on t1.dept_id=t2.id ;

      右外连接:查询的是右表所有数据,以及其交集部分

        语法:select 字段列表 from 表1 right[outer] join 表2 on 条件

            select * from emp t1 right join dept t2 on t1.dept_id=t2.id ;

 注意多张表的时候需要使用显示的内连接(减少字段的扫描),但是隐式的内连接显然更好理解。

    3.子查询

    查询工资最高的员工

      select*from emp where salary=(select max(salary) from emp);

    子查询的结果是单行单列的:

      子查询可以作为条件使用运算符去判断(><=)

      查询工资小于平均工资少的人

            select * from emp where emp.salary<(select avg(salary) from emp);

    子查询的结果是多行单列的:

      子查询可以作为条件,使用运算符in来判断

      查询财务部和市场部所有员工的信息

      select * from emp where dept_id in (select * from dept where name in ('财务部','市场部'));

    子查询的结果是多行多列的:

      子查询是多行多列的时候可以当做一个虚拟的表参与查询

      查询所有入职日期在2011-11-11之后入职的员工所有信息

      select * from dept t1,(select * from emp where emp.join_date>'2011-11-11') t2 where t1.id=t2.dept_id;

      或者使用普通查询

      select * from emp t1,dept t2 where t1.dept_id=t2.id and dept.join_date>'2011-11-11';
原文地址:https://www.cnblogs.com/feixiangdecainiao/p/10803400.html