SQL子查询什么时候用

概念
子查询
含义:
出现在其他语句中的select语句,称为子查询或内查询;
外部的查询语句称为主查询或外查询;

分类:
按子查询出现的位置分:

select后面:仅仅支持标量子查询

from后面:支持表子查询

where或having后面:支持标量子查询(单行)、列子查询(多行)、行子查询

exists后面(也被称为’相关子查询‘):支持表子查询

按结果集的行数不同分:

标量子查询(结果集为一行一列);

列子查询(结果集为一列多行);

行子查询(结果集为一行多列);

表子查询(结果集为多行多列);

一、where和having后面
特点
1、子查询放在小括号内

2、子查询一般放在条件的右侧

3、标量子查询一般搭配着单行操作符使用(< > >= <= <> =);列子查询一般搭配着多行操作符使用(in、any/some、all)

4、子查询的执行优先于主查询,因为主查询的条件用到了子查询的结果

标量子查询(单行)
1、查出价格比黄瓜贵的商品(where后面)

select * 
from good 
where price>(
    select price 
    from good 
    where name='黄瓜'
);
2、查出价格比黄瓜贵,类别是服装的商品(where后面)

select * 
from good 
where price>(
    select price 
    from good
    where name='黄瓜' 
) and tid=(
    select id
    from type
    where name='服装'
);
3、查出价格最低的商品名称和价格(where后面)

select name,price 
from good 
where price=(
    select min(price) 
    from good
);
4、查出最低价格大于蔬菜最低价格的类别名称和其最低价格和最低价格的商品名称(having后面和where后面一起使用)

select min(price),t.name,g.name
from good g
join type t
on g.tid=t.id
group by tid
having min(price)>(
    select min(price)
    from good 
    where tid=(
        select id 
        from type
        where name='蔬菜'
    )
);
标量子查询注意事项:子查询结果必须是一行一列;

列子查询(多行)
1、返回蔬菜和水果类别中所有商品名称

select *
from good
where tid in(
    select id
    from type
    where name='蔬菜'
    or name='水果'
);
 
//上面的in可以替换为 =any(any的意思是匹配子查询中任意一个)
select *
from good
where tid =any(
    select id
    from type
    where name='蔬菜'
    or name='水果'
);
2、返回除了蔬菜和水果以外的所有类别的商品

select *
from good
where tid not in(
    select id 
    from type
    where name='蔬菜'
    or name='水果'
);
 
//上面的not in可以替换为 <>all(all意思是匹配子查询的所有结果)
 
select *
from good
where tid <>all(
    select id 
    from type
    where name='蔬菜'
    or name='水果'
);
行子查询(多行多列或一行多列)
应用场景比较特殊,多个条件必须用等于

1、查询id最小价格最高的商品信息

select *
from good
where (id,price)=(
    select min(id),max(price)
    from good
);
二、exists后面的子查询(相关子查询)
select exists(select * from good);返回1或0

只关心exists括号里面的子查询是否为空,空返回0;不为空返回1;

案例1:查询有商品的类别名称

select name
from type t
where exists(
    select id
    from good g
    where g.tid=t.id
);
三、from后面
案例1、查询每个类别中价格高于本类别平均价格的商品

select g.name,g.price,g.tid 
from good g 
join (
    select avg(price) jprice,tid 
    from good
    group by tid
) e 
on g.tid=e.tid 
where g.price>jprice;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值