






















关联子查询是一种依赖外部查询结果的子查询,它的核心特点是:子查询中会引用外部查询的表或字段,因此会针对外部查询的每一行数据,动态执行一次子查询,形成“内外联动”的关系。
WHERE 子查询表.字段 = 外部表.字段),无法独立执行。假设有一张学生成绩表 scores(student_id, subject, score),要查询“每门科目中,分数高于该科目平均分的学生”,可用关联子查询:
SELECT student_id, subject, score
FROM scores s1 -- 外部查询表
WHERE score > (
-- 关联子查询:引用外部表的subject,计算当前科目的平均分
SELECT AVG(score)
FROM scores s2
WHERE s2.subject = s1.subject -- 子查询依赖外部表的subject
);
s1 的每一行(如 (101, 数学, 90));subject(数学),计算所有数学成绩的平均分;SELECT * FROM t WHERE id IN (SELECT id FROM t2))。关联子查询的逻辑直观,但性能可能较低(数据量大时需多次扫描表),适合简单场景;复杂场景建议用窗口函数替代。
例如leetcode的
3421. 查找进步的学生
# -------------关联子查询---------------------------------------
select s1.student_id, s1.subject,
s1.score as first_score,
s2.score as latest_score
from scores s1 join scores s2
on s1.student_id=s2.student_id and s1.subject=s2.subject
where s1.exam_date=
(select min(exam_date) from scores where student_id=s1.student_id and subject=s1.subject)
and s2.exam_date=
(select max(exam_date) from scores where student_id=s2.student_id and subject=s2.subject)
and s1.score<s2.score
group by s1.student_id,s1.subject
order by s1.student_id,s1.subject
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。