优化 LATERAL 连接与相关查找
学习 LATERAL 连接如何让子查询引用前面表中的列,以及如何用它们将缓慢的相关子查询替换为高效的逐行查找
优化 LATERAL 连接与相关查找 是 CoddyKit 上的免费 PostgreSQL Performance & Query Optimization 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 PostgreSQL Performance & Query Optimization 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 PostgreSQL Performance & Query Optimization 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is a LATERAL Join?
A LATERAL join lets a subquery in the FROM clause reference columns from tables listed before it. Without LATERAL, a subquery in FROM cannot see the outer rows.
The Problem It Solves
Suppose you want, for each customer, their three most recent orders. A plain join cannot easily limit rows per customer. LATERAL evaluates the subquery once per outer row, so a per-row LIMIT works.
Basic Syntax
Place LATERAL before the subquery and reference the outer table inside it.
SELECT c.name, o.id, o.total
FROM customers c
CROSS JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 3
) o;LEFT JOIN LATERAL
Use LEFT JOIN LATERAL ... ON true when you still want outer rows that have no matching subquery results, such as customers with no orders.
SELECT c.name, o.id
FROM customers c
LEFT JOIN LATERAL (
SELECT id FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC LIMIT 1
) o ON true;LATERAL vs Correlated Subquery
A correlated subquery in the SELECT list can only return one column per row. LATERAL can return multiple columns and multiple rows, making it far more flexible.
Indexing for LATERAL
Because the subquery runs once per outer row, the inner filter and sort must be index-backed. Create a composite index matching the WHERE and ORDER BY columns.
CREATE INDEX idx_orders_cust_created
ON orders (customer_id, created_at DESC);Reading the Plan
A well-optimized LATERAL shows a Nested Loop with an Index Scan on the inner side. If you see a Seq Scan inside the loop, the supporting index is missing.
EXPLAIN ANALYZE
SELECT c.name, o.id
FROM customers c
CROSS JOIN LATERAL (
SELECT id FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC LIMIT 3
) o;LATERAL with Set-Returning Functions
LATERAL also works with functions like unnest or jsonb_array_elements, expanding array columns per row.
SELECT p.id, tag
FROM products p
CROSS JOIN LATERAL unnest(p.tags) AS tag;Top-N Per Group Pattern
The most common use of LATERAL is the top-N-per-group query. It is usually faster than window-function approaches when N is small and an index supports the order.
When to Avoid LATERAL
If the outer table is huge and the inner subquery has no supporting index, running it millions of times is slow. In that case a window function or a single aggregated join may win. Always measure both.
Passing Computed Values Forward
LATERAL can also compute an intermediate value and reuse it in later expressions, avoiding repeating the same calculation. Each LATERAL block sees the columns produced before it.
SELECT o.id, m.margin
FROM orders o
CROSS JOIN LATERAL (
SELECT o.total - o.cost AS margin
) m
WHERE m.margin > 0;Quick Check
Test your LATERAL knowledge.
Recap
You learned LATERAL joins:
- They let a FROM-clause subquery see earlier tables' columns
- Perfect for top-N-per-group and per-row lookups
- Use
LEFT JOIN LATERAL ... ON trueto keep unmatched outer rows - Back the inner filter and sort with a composite index
- Confirm a Nested Loop + Index Scan in the plan
常见问题解答
「优化 LATERAL 连接与相关查找」课时是免费的吗?
是的 — 「优化 LATERAL 连接与相关查找」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 PostgreSQL Performance & Query Optimization 课程的其余内容,请升级到 CoddyKit PRO。 PostgreSQL Performance & Query Optimization 课程共包含 4 节课。
「优化 LATERAL 连接与相关查找」这节课中我会学到什么?
学习 LATERAL 连接如何让子查询引用前面表中的列,以及如何用它们将缓慢的相关子查询替换为高效的逐行查找 你通过在浏览器中直接运行的动手代码来练习 PostgreSQL Performance & Query Optimization,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 PostgreSQL Performance & Query Optimization 需要有经验吗?
无需任何先前经验。CoddyKit 上的 PostgreSQL Performance & Query Optimization 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「优化 LATERAL 连接与相关查找」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 PostgreSQL Performance & Query Optimization 课中编写并运行代码吗?
能。每节 PostgreSQL Performance & Query Optimization 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 了解连接算法
- 重写复杂连接
- 子查询、CTE 与连接的比较
- 优化 LATERAL 连接与相关查找