现在我的查询看起来像这样。 %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
时执行此操作,还是必须执行某种子查询?
答案 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