子查询 附带源代码sql

  1. 理解
    一个查询语句中内嵌另一个完整的查询语句,被嵌套的语句 称为子查询 或者内查询
    外面的语句称为主查询 或者外查询

  2. 语法
    select (子查询)
    from (子查询)
    where (子查询)

  3. 特点

    1. 子查询 必须写在小括号中
    2. 子查询 优先执行 ,主查询需要用到子查询的结果
    3. 子查询结果
      单行子查询:结果只有一个 搭配的符号 = > < >= <= <>
      多行子查询:结果多个 搭配的符号 in / not in all() any()
      能单表的就不多表
      能多表就不子查询
# 1. 单行子查询
# 案例1:查询薪资比'smith'的薪资高的员工信息
-- 先查出smith的薪资
select sal from EMP where ename = 'smith';
select * from EMP where sal > (select sal from EMP where ename = 'smith');

结果:
在这里插入图片描述


# 案例2:查询部门地址loc 是 NEW YORK或者CHICAGO的部门中所有的员工的信息
-- 先找部门地址loc 是 NEW YORK或者CHICAGO 部门编号
select deptno from DEPT where loc in('NEW YORK','CHICAGO');

select * from EMP 
where deptno in(select deptno from DEPT where loc in('NEW YORK','CHICAGO'));

结果
在这里插入图片描述

#查询员工的最高薪资并显示员工的姓名
select sal,ename from EMP order by sal desc limit 1;

方式2
-- 最高薪资
select max(sal) from EMP;

select sal,ename from EMP where sal = (select max(sal) from EMP);

结果
在这里插入图片描述

# 案例3:查询其他部门中比部门10中的 任意一个员工薪资都低的员工薪资、名字
-- 求出部门10的最低薪资
select min(sal) from EMP where deptno = 10;

select ENAME from EMP where deptno != 10  
and sal < (select min(sal) from EMP where deptno = 10);

结果
在这里插入图片描述

-- all()  所有
-- 查询小于部门10的薪资
select sal from EMP where deptno = 10;

select sal from EMP where deptno != 10 
and sal < all(select sal from EMP where deptno = 10);

在这里插入图片描述

# 案例4:查询其他部门中比部门10中的 任一一个员工薪资都低的员工薪资、名字

-- 求出部门10的最高薪资
select max(sal) from EMP where deptno = 10;

select * from EMP where deptno != 10 
and sal < (select max(sal) from EMP where deptno = 10);

结果:
在这里插入图片描述

-- any()

-- 查询出部门10的薪资
 select sal from EMP where deptno = 10;

select * from EMP where deptno != 10
and sal < any(select sal from EMP where deptno = 10);

结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值