在我的 postgres 資料庫中,我有一個帖子和評論表:
帖子:
id title
1 post1
2 post2
3 post3
評論:
id post_id content
1 1 a
2 1 b
3 1 c
4 2 d
5 3 e
6 3 f
7 3 g
我如何選擇評論where post_id in (1,3),但每條限制為 2 個post_id,以便我得到:
id post_id content
1 1 a
2 1 b
5 3 e
6 3 f
編輯:對于我的特定情況,我能夠通過回圈遍歷 post_ids 陣列以編程方式構造查詢。
在考慮:
(select * from comments where post_id = 1 limit 2)
union all
(select * from comments where post_id = 3 limit 2)
uj5u.com熱心網友回復:
使用ROW_NUMBER:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY post_id ORDER BY content) rn
FROM comments
WHERE post_id IN (1, 3)
)
SELECT id, post_id, content
FROM cte
WHERE rn <= 2;
uj5u.com熱心網友回復:
您可以使用橫向連接。
select foo.* from
posts
cross join lateral
(select * from comments where post_id=posts.id order by content limit 2) foo
where post_id IN (1, 3);
在你的問題中,不清楚訂購什么,所以我只是從蒂姆的回答中復制了訂單。這有可能比 row_number() 快得多,因為它會對每個相關帖子的所有評論進行編號,然后過濾掉數字較大的評論。雖然每個柱子的橫向只數到 2,然后停止。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/399548.html
標籤:PostgreSQL的
