1.多表查询概念:从多张表查询数据

2.分类:连接查询和子查询。

有两张表A、B

连接查询: 内连接      相当于查询A、B交集数据

例1:select * from emp,dept where emp.dep_id=dept.id;

                    外连接      左外连接:相当于查询A表所有数据和交集部分数据

                                     右外连接:相当于查询B表所有数据和交集部分数据

子查询:查询中嵌套查询。

3.内连接(同时查询两张表的列)

 隐式内连接         select 字段列表 from 表一,表二 where 条件;

   如上面的例子:select * from emp,dept where emp.dep_id=dept.id;

          在没有条件语句的情况下返回笛卡尔积(排列组合)

   例2:select emp.name,emp.gender,dept.name  from emp,dept where emp.dep_id=dept.id;

  显式内连接       select 字段列表 from 表一 inner join 表二 on 条件;  

    例3:select * from emp iennr join dept on emp.dep_id = dept.id;           innner可以省略

4.外连接

    左外连接     select 字段列表 from 表1 left join 表2 on 条件;

     例4:查询emp表所有数据和对应的部门信息

                select * from emp left join dept on emp.dep_id = dept.id; 

    右外连接     select 字段列表 from 表1 right join 表2 on 条件;

    例5:查询dept表所有数据和对应员工信息

                  select * from emp right join dept on emp.dep_id = dept.id;

             或:  select * from  dept left join emp on emp.dep_id = dept.id;(工作中最常使用left join)

5.子查询

  (1)概念:查询中嵌套查询。

           子查询分为:单行单列         select 字段列表 from 表 where 字段名 = 子查询;

                                多行单列          select 字段列表 from 表 where 字段名  in 子查询;

                                多行多列          select 字段列表 from (子查询)where   条件;

        例1:查询班级中成绩高于叶淑华的学生的信息:

           select * from stus where score>(select score from stus where name = "叶淑华");

         

     例2:查询财务部和销售部的所有员工信息:

             select * from emp where dep_id in (select id from dept where dept_name = "财务部" or dept_name = "销售部")

            

IN 操作符用于匹配一组值,其后也可以接一个 SELECT 子句,从而匹配子查询得到的一组值。

         例3:查询年龄大于20的员工信息和部门信息

                 思路:先列出年龄大于20岁的员工的所有信息,作为虚拟表与dep_id进行内连接

      select * from (select * from emp where age>20)t1,dept where t1.dep_id =  dept.id;

t1是别名,select * from emp where age>20作为虚拟表。

多表查询案例:

职位表                                部门

 薪资等级表

                  员工表 

 

注意第三条要求里,由于peach的工资不在工资区间里,所以查询出来没有peach的记录。(对连接条件的理解)

第五条要求中,第一行是仅分组,第二行是分组后的表作为虚拟表跟dept连接,然后查询。

第五条还可写成别名形式:

select * from dept,(select count(emp.id) 人数,emp.dep_id 部门编号 from emp group by dep_id)t1 where dept.id = t1.部门编号

运行结果:

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐