如何 select 一列中每个不同的元素只有两行 (PostgreSQL 9.3.5)
How to select only two rows for each distinct element in a colum (PostgreSQL 9.3.5)
现在我有一个看起来像这样的查询。 %s
用于 psycopg2:
SELECT DISTINCT ON (p1.creating_user_id) p1.post_id, p1.message
FROM posts p1
LEFT OUTER JOIN post_relations pr1 ON pr1.post_id=p1.post_id AND pr1.receiving_user_id=%s
WHERE p1.creating_user_id IN (SELECT ur2.user_b_id
FROM user_relations AS ur2
WHERE ur2.user_a_id=%s
AND ur2.friend=true)
ORDER BY p1.creating_user_id, p1.created_utc DESC
我如何将此查询更改为 return 两行以达到 creating_user_id 而不是只有一行?有没有办法在仍然使用 SELECT DISTINCT
的同时做到这一点,还是我必须做某种子查询?
一个window function可以做到
select post_id, message
from (
select
p1.post_id, p1.message,
row_number() over(
partition by p1.creating_user_id
order by p1.created_utc desc
) as rn
from
posts p1
left outer join
post_relations pr1 on pr1.post_id = p1.post_id and pr1.receiving_user_id = %s
where p1.creating_user_id in (
select user_b_id
from user_relations
where user_a_id = %s and friend = true
)
) s
where rn <= 2
现在我有一个看起来像这样的查询。 %s
用于 psycopg2:
SELECT DISTINCT ON (p1.creating_user_id) p1.post_id, p1.message
FROM posts p1
LEFT OUTER JOIN post_relations pr1 ON pr1.post_id=p1.post_id AND pr1.receiving_user_id=%s
WHERE p1.creating_user_id IN (SELECT ur2.user_b_id
FROM user_relations AS ur2
WHERE ur2.user_a_id=%s
AND ur2.friend=true)
ORDER BY p1.creating_user_id, p1.created_utc DESC
我如何将此查询更改为 return 两行以达到 creating_user_id 而不是只有一行?有没有办法在仍然使用 SELECT DISTINCT
的同时做到这一点,还是我必须做某种子查询?
一个window function可以做到
select post_id, message
from (
select
p1.post_id, p1.message,
row_number() over(
partition by p1.creating_user_id
order by p1.created_utc desc
) as rn
from
posts p1
left outer join
post_relations pr1 on pr1.post_id = p1.post_id and pr1.receiving_user_id = %s
where p1.creating_user_id in (
select user_b_id
from user_relations
where user_a_id = %s and friend = true
)
) s
where rn <= 2