本章本质上是对表进行嵌套查询
子查询
本质是对表的嵌套查询
看例子就明白了
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
)