我有3张桌子,如下所述:
所有三个表和输出image
post_comments posts comments
评论comments
现在,我想获取具有最高点赞评论的帖子,并且该评论的状态在Postgres中应该处于活动状态。
输出:
注意:自从发布1以来,最高喜欢的评论处于无效状态。
我尝试过这样的事情:
select "posts".*
from "posts"
inner join (select id, max(likes) l from comments innner join post_comments on comments.id = post_comments.alert_id and post_comments.post_id = posts.id) a on posts.id = a.cid ...
这还不完整,但我无法做到这一点。
答案 0 :(得分:2)
在Postgres中,您可以使用distinct on
来获得每则帖子最喜欢的活动评论:
select distinct on (pc.post_id) pc.*
from post_comments pc join
comments c
on pc.comment_id = c.id
where c.status = 'active'
order by pc.post_id, c.likes desc;
我认为这与您想要的东西很相关。
答案 1 :(得分:0)
尝试这样的事情:
SELECT posts.*, MAX(likes) l
FROM posts
JOIN post_comments ON post_id = posts.id
LEFT JOIN comments ON comment_id = comments.id
GROUP BY posts.id