sql多表查询

本文详细介绍了数据库中的多表查询,包括内连接、外连接(左连接和右连接)以及子查询的使用方法。通过实例展示了如何从员工表、部门表和薪资等级表等多个表中获取所需信息,强调了连接条件的理解和子查询在复杂查询中的应用。最后,提供了实际案例来加深对外连接和分组查询概念的理解。
摘要由CSDN通过智能技术生成

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.部门编号

运行结果:

 

  • 13
    点赞
  • 83
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值