05 MySQL编写复杂查询

本章本质上是对表进行嵌套查询

子查询

本质是对表的嵌套查询

看例子就明白了

select
*
from products
where unit_price > (
	select unit_price
    from products
    where product_id = 3
)
-- 我们要选择id为

IN

我们可以

-- 选取没有发票的人
use sql_invoicing;
select name
from clients
where client_id
not in(
	select distinct client_id
    from invoices
)

ALL

作用相当于对子查询中所有的结果进行运算,例如:筛选出来数值,那么套用ALL关键字就是比这些所有的数都要大

select *
from invoices
where invoice_total > all(
	select invoice_total
    from invoices
    where client_id = 3
)

--  相当于

select *
from invoices
where invoice_total > (
	select max(invoice_total)
    from invoices
    where client_id = 3
)

ANY

发票总额高于这段子查询返回的任意值的信息,= any等价于in

相关子查询

如果子查询中有外查询的引用或有相关性,就成为相关子查询

一般来说消耗资源很大,但是实际运用的时候也比较常用

select *
from invoices inv
where invoice_total > (
	select avg(invoice_total)
    from invoices
    where client_id = inv.client_id
)

EXISTS

使用exists关键字,查看子查询中有没有存在符合子查询条件的行

使用exists关键字,与一般的先进行括号里面的子查询表不同,它会返回一个指令说明这个子查询中是否有符合这个搜索条件的行,只要找到一条,就返回true

如果使用in返回了一个比较庞大的结果集,我们使用exists效率就会很高,因为这时候子查询并没有真的把结果集返回给外查询

select *
from products
where not exists (
	select product_id
    from order_items
    where product_id = products.product_id
)

SELWCT中的子查询

select
	client_id,
    name,
    (select sum(invoice_total) from invoices where client_id = c.client_id) as total_sales,
    (select avg(invoice_total) from invoices) as average,
    (select average - total_sales) as differen
from clients c

FROM中的子查询

我们使用上面select生成了一张我们查询的表

select *
from
(
    select
	client_id,
    name,
    (select sum(invoice_total) from invoices where client_id = c.client_id) as total_sales,
    (select avg(invoice_total) from invoices) as average,
    (select average - total_sales) as differen
from clients c
)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值