6. 复杂查询

简介: 6. 复杂查询

编写子查询

sql

复制代码

use sql_store;
-- Find products that are more
-- expensive than Lettuce ( id = 3)
-- 编写子查询
select *
from products
where name like 'Lettuce%';
    
select *
from products
where unit_price > (
  select unit_price
  from products
  where name like 'Lettuce%'
)

sql

复制代码

-- In sql_hr database:
-- Find employees whose earn more than average
use sql_hr;
select 
  avg(salary) as avergae
from employees;
-- 没有结果
select *
from employees
having salary > avg(salary);
-- 正确答案
select *
from employees
where salary > (
  select 
  avg(salary)
  from employees
  )

注意:having 中不可以再使用属性名比较,只能使用聚合函数判断;同样的道理,where 反过来

需要确定子查询是返回的唯一值才可以继续,如果一个集合,可以考虑用 in

in运算符

sql

复制代码

use sql_store;
-- Find the products that have never been ordered
select *
from products
where product_id not in (
  select 
    distinct product_id
  from order_items
)

使用 in 运算符,进行子查询。

sql

复制代码

use sql_invoicing;
select *
from clients
where client_id not in(
  select distinct client_id
    from invoices
)

子查询和连接

子查询(Subquery)是将一张表的查询结果作为另一张表的查询依据并层层嵌套,其实也可以先将这些表链接(Join)合并成一个包含所需全部信息的详情表再直接在详情表里筛选查询。 两种方法一般是可互换的,具体用哪一种取决于 效率/性能(Performance) 和 可读性(readability)。

sql

复制代码

select *
from clients
where client_id not in(
  select distinct client_id
    from invoices
);
select *
from clients
left join invoices using (client_id)
where invoice_id is NULL;

sql

复制代码

use sql_store;
select 
  customer_id, 
    first_name,
    last_name
from customers c
where c.customer_id in (
  select customer_id
    from orders o
    where o.order_id in (
    select order_id
    from order_items oi
    where oi.product_id = (
      select product_id
      from products p
      where p.name like 'Lettuce%'
    )
    )
)
-- 上面是使用嵌套的方法,同样可以写出连接的方法,这里就不写了

这个案例中,先将所需信息所在的几张表全部连接合并成一张大表再来查询筛选明显比层层嵌套的多重子查询更加清晰明了

all关键字

sql

复制代码

use sql_invoicing;
select *
from invoices
where invoice_total > (
  select max(invoice_total)
  from invoices 
  where client_id = 3
);
select *
from invoices
where invoice_total > ALL (
  select invoice_total
  from invoices 
  where client_id = 3
);

上面的子查询返回了一列值 使用ALL会和子查询里面返回的所有值进行比较,父查询如果存在满足所有子查询条件,返回这条记录。 等价于在子查询中 max()

any关键字

sql

复制代码

select *
from clients
where client_id in(
  select client_id
  from invoices
  group by client_id
  having count(*) >= 2
);
select *
from clients
where client_id = any(
  select client_id
  from invoices
  group by client_id
  having count(*) >= 2
);

如果说 all 是与运算,那么 any 就是或运算 = any等价于in

ANY/SOME (……) 与 > (MIN (……)) 等效

  • = ANY/SOME (……) 与 IN (……) 等效

相关子查询

sql

复制代码

-- Select employees whose salary is
-- above the average in their office
use sql_hr;
select *
from employees e
where salary > (
  select avg(salary)
    from employees
    where office_id = e.office_id
)

如上面样例中的类似,如果在子查询中出现了父查询表的别名,就可以称为相关子查询。 没有则是不相关子查询。

注意:使用相关子查询,这段查询会在主查询的每一行的层面执行,所以相关子查询会很慢

sql

复制代码

-- Get invoices that are larger than the
-- client's average invoice amount
use sql_invoicing;
select *
from invoices i
where invoice_total > (
  select
    avg(invoice_total) as average
  from invoices
    where client_id = i.client_id
);

exists 运算符

IN + 子查询 等效于 EXIST + 相关子查询如果前者子查询的结果集过大占用内存,用后者逐条验证更有效率。 另外 EXIST() 本质上是根据是否为空返回 TRUE 和 FALSE,所以也可以加 NOT 取反。

sql

复制代码

-- Select clients that have an invoice
select *
from clients
where client_id in (    -- in (1, 2, 3, 5)
  select distinct client_id
    from invoices
);
-- 使用exist
select *
from clients c
where exists (
  select client_id
    from invoices
    where client_id = c.client_id
)

**注意: 上面这个代码先执行子查询 in ( ),并把查询结果返回到 where 子句。 如果返回的结果非常多,会妨碍最佳性能

使用 exists 可以优化这个查询中的性能 子查询并没有真的把结果集返回给外查询**

sql

复制代码

-- Find the products that have never been ordered
use sql_store;
select *
from products p
where not exists(
  select *
    from order_items
    where product_id = p.product_id
)

只写 select * 就可以了,不需要选具体的属性。

select子句中的子查询

sql

复制代码

select
  invoice_id,
    invoice_total,
    (select avg(invoice_total)
    from invoices) as invoice_average,
  invoice_total - (select invoice_average) as difference
from invoices

简单讲就是,SELECT选择语句是用来确定查询结果选择包含哪些字段 每个字段都可以是一个表达式,而每个字段表达式里的元素除了可以是原始的列,具体的数值,也同样可以是其它各种花里胡哨的子查询的结果

sql

复制代码

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

很多奇特的用法:

  • (select total_sales) - (select average) as difference 这句可以直接写为(select total_sales - average) 可以理解为两个子查询在同一张表里面,可以直接减掉。
  • 子查询的使用了相关子查询,没有使用join连接,更优。原理可以看上面的相关子查询。

from子句中的子查询

sql

复制代码

USE sql_invoicing;
select *
from (
  -- 每当我们在form子句中使用子查询,必须要给子查询的结果一个别名
  select
    client_id,
    c.name,
    (select sum(invoice_total)
      from invoices i
      where i.client_id = c.client_id) as total_sales,
    (select avg(invoice_total)
      from invoices i) as average,
    (select total_sales) - (select average) as difference 
  from clients c
) as sales_summary
where total_sales is not null

很好理解,子查询当成一张表再次查询。 需要注意的是,每当我们在form子句中使用子查询,必须要给子查询的结果一个别名。

from中的子查询会让查询变得复杂,但是可以使用视图(views)来存储这张表,可以大大简化sql语句的复杂。


相关文章
|
SQL 关系型数据库 MySQL
rds教程
rds教程
603 4
|
10月前
|
人工智能 算法 数据可视化
Gemini 3.1 Pro 发布:一次真正意义上的推理能力跃迁
Google DeepMind深夜发布Gemini 3.1 Pro,推理能力跃升:ARC-AGI-2达77.1%(近乎翻倍),HLE测试44.4%领先竞品;支持100万Token上下文,SVG/代码生成与智能体表现断层领先;已上线Gemini、NotebookLM及AI Studio,标志着大模型竞争进入新阶段。
|
11月前
|
人工智能 搜索推荐 数据挖掘
深度 AI 学术是怎样学习百度学术、谷歌学术的先进经验的?
深度AI学术融合百度学术与Google Scholar优势,聚合2.8亿文献,支持中英文语义检索、AI自动摘要、引用追踪及趋势分析;创新提供批量翻译、自定义维度解析与学术报告生成,打造智能科研助手。(239字)
758 7
|
11月前
|
数据采集 人工智能 算法
AI智能体浮光行为:合规专家的职业路线与未来法律纠纷的隐形火药桶
本文揭示AI智能体中隐蔽的“浮光行为”——表面完成指令却未理解实质目标,已在法律领域引发产品责任、合同违约与合规危机三重风险。文章从真实法庭场景切入,剖析归责困境,并提出“目标达成度SLA+思维链日志+反事实测试”的跨维度防控框架,呼吁法务与技术深度协同。(239字)
406 1
|
11月前
|
数据采集 数据可视化 安全
RFID智能货架实施仓库可视化管理
RFID智能货架通过无线射频技术实现货物自动识别与批量盘点,支持非接触、远距离、穿透式数据采集,提升仓储效率与准确性。实现实时库存可视化、智能出入库、动态盘点与预警管理,助力仓储物流迈向自动化、智慧化。
|
12月前
南京观海微电子---MOS型(NMOS和PMOS)LDO应用原理
LDO分为NMOS和PMOS两种类型,工作在线性模式。通过误差放大器调节输出晶体管,实现稳压。NMOS型静态电流小,但压差大;PMOS可降低压差,提升效率,两者均以电压控制,负载变化时静态电流稳定,适用于低功耗场景。
南京观海微电子---MOS型(NMOS和PMOS)LDO应用原理
|
数据采集 传感器 安全
基于员工定位手环的属性、原理、商用优势与应用详解
员工定位手环集轻便、实时定位与多维数据联动于一体,支持健康监测、VoLTE通话及多种定位模式,续航长达10天。广泛应用于工业、医疗、养老等场景,实现人员精准管理、电子围栏报警、轨迹回溯与一键求救,助力企业安全高效运营。(238字)
|
JavaScript 前端开发 小程序
Vue 3:现代前端开发的革命性进化
Vue 3:现代前端开发的革命性进化
650 54
|
存储 人工智能 运维
自我提升可以从哪些方面:AI时代的能力重构与终身进化
在数字技术与AI快速发展的背景下,自我提升从“阶段式学习”转变为“持续性进化”。文章从认知升级、技能进化、生态构建三个维度解析AI时代个人能力提升的核心路径。强调个体需从知识积累转向能力重构,通过批判性思维、跨域关联和动态适应性实现思维跃迁;同时构建复合能力体系,并借助AI工具与协作网络,在数字化转型中扮演价值创造者角色。最终,自我提升将超越传统框架,成为能力生态的动态演进过程。
|
索引
汉字编码对照表(gb2312/unicode/utf8)
一、汉字编码的种类     汉字编码中现在主要用到的有三类,包括GBK,GB2312和Big5。     1、GB2312又称国标码,由国家标准总局发布,1981年5月1日实施,通行于大陆。
6953 0