SELECT children.*
FROM
children
JOIN parents ON (children.parent_id = parents.id)
WHERE
parents.id IN (1,2,3,4,5)
ORDER BY children.age DESC
LIMIT 1
这会将整个查询的结果限制为 1。相反,我希望在 parents.id IN (1,2,3,4,5)
下为每个父项返回 1 个子项,因此我希望查询返回 5。
换句话说,每个 parent 都有多个 child ,我想返回每个 parent 的一个最大的 child
有没有办法做到这一点?
最佳答案
从您的示例查询来看,根本不需要父表(因为您不需要其中的任何列)。
应该执行以下操作:
select id,
parent_id,
age,
... other columns ...
from (
select id,
parent_id,
age,
... other columns ...,
row_number() over (partition by parent_id order by age) as rn
from children
where parent_id in (1,2,3,4,5)
) as ch
where rn = 1
order by age;
通过更改窗口函数内的 order by
子句,您可以控制在有多个子项时返回哪个子项。在本例中,我选择最小的(按年龄排序
)
看来您是 SQL 新手,因此为了了解窗口函数 (row_number() over (...)
) 的使用,您可能需要在其上运行内部选择拥有并看看会发生什么。
如果您简化了实际语句,并且确实需要 parents
表中的列,则可以将内部查询与 parents
表连接起来:
select p.*, -- all columns from the parents table
ch.* -- all columns from the children table
from parents p
join (
select id,
parent_id,
age,
... other columns ...,
row_number() over (partition by parent_id order by age) as rn
from children
) as ch on ch.parent_id = p.id and ch.rn = 1
where p.id in (1,2,3,4,5)
order by ch.age;
使用 Postgres 的 distinct on
运算符可以达到相同的效果,实际上可能更快。
关于sql - postgresql:每个 IN 子句的 LIMIT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21154752/