sql - 如果我们只对第一个匹配的子行感兴趣,如何在 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
将始终相同。
所以我想从P
with中获取所有记录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
解决方案
试试这个:
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
推荐阅读
- amazon-web-services - 使用 Golang 从 Lambda 调用 AppSync Mutation
- python - 对于列表列表,将字典与 collections.defaultdict 合并
- docker - 管道 docker network ls 进行切割
- python - Python 从 complex128 转换为 float64
- java - JDK 11 编译类文件失败并出现 OOM 异常
- python - 根据行值返回列的平均值
- c++ - GDB MinGW-w64如何跨过函数指针?
- php - 单击登录按钮转到 404 Page Not Found (CodeIgniter)
- php - 使用 cURL 获得 While 循环?
- java - 正则表达式(正则表达式)。如何忽略或排除介于两者之间的所有内容?