如何为列中的每个不同元素仅选择两行(PostgreSQL 9.3.5)

时间:2015-01-16 21:58:11

标签: postgresql

现在我的查询看起来像这样。 %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

如何更改此查询以返回两行以进入到create_user_id而不是只有一行?有没有办法在使用SELECT DISTINCT时执行此操作,还是必须执行某种子查询?

1 个答案:

答案 0 :(得分:3)

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