SQL 嵌套子查询

多表单行嵌套

  • 例:
    • 职工_tb: 工资,仓库号
    • 仓库_tb: 城市,仓库号
      显示工资不大于北京平均工资的职工信息
select * from 职工 where 工资!>(
    select avg(工资) from 职工 where 仓库号 in 
    (select 仓库号 from 仓库 where 城市='北京') )

exists 真假值

  • 例1.1:显示有职工的仓库信息
select * from 仓库 where exists(
    select 仓库号 from 职工 where 仓库号=仓库.仓库号 
)
  • 例1.2:显示没有职工的仓库信息
select * from 仓库 where not exists
(select * from 职工 where 仓库号=仓库.仓库号)
  • 例2:显示有职工且工资大于2000的仓库信息
select * from 仓库 where exists
(
    select * from 职工 where 
    (
        仓库号=仓库.仓库号 and 工资>2000
    )
)
  • 例3:显示有职工,且城市不为空的仓库信息
select * from 仓库 where exists(select * from 职工 where 仓库号=仓库.仓库号)
and 城市 is not null

any 任一

  • 例:显示工资大于wh2仓库中任一名职工工资的职工信息
select * from 职工 where 工资>any(select 工资 from 职工 where 仓库号='wh2')

或者

select * from 职工 where 工资>(select min(工资) from 职工 where 仓库号='wh2')

all

  • 例:显示工资小于等于wh2仓库中所有职工工资的职工信息
select * from 职工 where 
    工资<=ALL(select 工资 from 职工 where 仓库号='wh2')

产生虚拟表的嵌套子查询

  • 例:显示职工姓名、工资及所在仓库的平均工资
select 姓名,工资,各仓库平均工资 from(select *,各仓库平均工资=
case
    when 仓库号='wh1' then (select avg(工资) from 职工 where 仓库号='wh1'
    when 仓库号='wh2' then (select avg(工资) from 职工 where 仓库号='wh2'
    when 仓库号='wh3' then (select avg(工资) from 职工 where 仓库号='wh3'
end
from 职工)my_table

tip:my_table是产生的虚拟表名

group by 产生虚拟表

group by + having

  • 例:显示平均工资大于1700的不同仓库的仓库号、平均工资、职工人数、最大工资
select * from (仓库号,avg(工资) as 平均工资,
    sum(工资)/avg(工资) as 职工人数,max(工资) as 最大工资
from 职工 group by 仓库号 having avg(工资)>1700 )my_table

group by + order by

  • 例:按平均工资从高到低显示不同仓库的仓库号、平均工资、职工人数、最大工资
select * from (仓库号,avg(工资) as 平均工资,
    count(*) as 职工人数,max(工资) as 最大工资
from 职工 group by 仓库号)my_table
order by 平均工资 desc

group by + where

  • 例:显示工资大于不同仓库平均工资的职工信息
select * from 职工 where 工资>ALL(select avg(工资) from 职工 group by 仓库号)

tip:这里只能用all实现

内外层嵌套子查询

※难点
- 例:显示不同职工经手订单金额最大的订单信息

select a.* from 订单 a where 
    金额=(select max(金额) from 订单 where 职工号=a.职工号 )

tip:这里用group by是错误的,group by会分组显示所有信息

猜你喜欢

转载自blog.csdn.net/weixin_41471128/article/details/81457643