多表查询

连接查询:

  内连接:AB交集

    隐式内连接

    select    t1.name,   t1.age,  t2.dname  from emp t1,  dept  t2  where t1.dep_id=t2.did; --起别名简化书写

    显式内连接

    select * from emp join dept on emp.dep_id=dept_did;  --join和 inner join一个意思

  外连接:

    左外连接:A和AB交集

      查emp所有数据和对应部门信息

      select * from emp left join dept on emp.dep_id=dept.id;    --查emp所有数据

    右外连接:B和AB交集

      select * from emp right join dept on emp.dep_id=dept.id;       --查dept所有数据

 

子查询;单行单列/多行单列/多行多列

  单行单列:

  查比猪八戒工资高的员工信息:

    分两步:①查猪八戒工资

        select salary from emp where name='猪八戒';    -- 查出了3600

        ②查工资高于猪八戒的工资

        select * from emp where salary>3600;

    合二为一:

      select * from emp where salary>(select salary from emp where name='猪八戒');

  多行单列:

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

     同理两步走:

      select * from emp where dep_id in( select did from dept where dname='财务部' or dname='市场部');

  多行多列:

    查入职日期是‘2022-2-2’之后,的员工信息和部门信息:

    分两步

      select *from emp where join_date >'2022-2-2';  -- 查出在这之后的员工

      select *from (select *from emp where join_date >'2022-2-2') t1,dept where t1.dep_id=dept.did;     --在第一步查出的表之上查

  

      

posted @ 2023-02-28 15:30  大灰狼21  阅读(18)  评论(0)    收藏  举报