首页 > 解决方案 > 如果我们只对第一个匹配的子行感兴趣,如何在 Oracle 中优化 JOIN?

问题描述

我有父表,可以说 P,带有 Id、Name 和 Type。

P(
  id (pk),
  name,
  type (type in (1..10) )
)

我有一个引用 P 的子表,假设该表称为 B:

B (
  id,
  date,
  other columns,
  parent_id
)

现在问题来了:表P没有那么多记录,但表B确实很大。如果是Type = 3,则父记录中的日期B将始终相同。

所以我想从Pwith中获取所有记录type = 3,并从 table 中获取相应的 Date B。考虑到 B 很大,最好的方法是什么?

我想写一些类似的东西

Select b.parent_id, p.name, max(b.date)
from B b
join P p on p.id = b.parent_id
group by b.parent_id, p.name
where p.type = 3

在这里max(b.date)min(b.date)剂量无关紧要,因为日期是相同的。但是桌子B很大。P仅选择 from并加入 to不是更好吗B,例如“具有最小 id 的子行”,或者基本上是任何子行?

Select p.id, p.name, b.date
from P p
join B b on (p.id = b.parent_id and "take only first matching row")
where p.type = 3

标签: sqloraclequery-optimization

解决方案


试试这个:

Select p.id, p.name, (select b.date from B where p.id = b.parent_id and rownum = 1) date
from P p
where p.type = 3

推荐阅读