尽管我在这里阅读了所有类似的问题,但我无法弄清楚如何在组内进行限制。阅读 PSQL 文档也无济于事 :( 考虑以下几点:
CREATE TABLE article_relationship
(
article_from INT NOT NULL,
article_to INT NOT NULL,
score INT
);
我想获得按分数排序的每个给定文章 ID 的前 5 篇相关文章的列表。
这是我尝试过的:
select DISTINCT o.article_from
from article_relationship o
join lateral (
select i.article_from, i.article_to, i.score from article_relationship i
order by score desc
limit 5
) p on p.article_from = o.article_from
where o.article_from IN (18329382, 61913904, 66538293, 66540477, 66496909)
order by o.article_from;
它什么也不返回。我的印象是外部查询就像循环,所以我想我只需要源 ID。
另外,如果我想加入articles
有列的表格id
并title
在结果集中获取相关文章的标题怎么办?
我在内部查询中添加了连接:
select o.id, p.*
from articles o
join lateral (
select a.title, i.article_from, i.article_to, i.score
from article_relationship i
INNER JOIN articles a on a.id = i.article_to
where i.article_from = o.id
order by score desc
limit 5
) p on true
where o.id IN (18329382, 61913904, 66538293, 66540477, 66496909)
order by o.id;
但这让它变得非常非常缓慢。