【问题标题】:Group by on join and calculate max of groups加入时分组并计算最大组数
【发布时间】:2019-04-24 11:09:04
【问题描述】:

我有 3 个表,如下所述:

所有三个表和输出image

帖子post table

post_cmets posts comments

cmetscomments

现在我想获取最喜欢 cmets 的帖子,并且该评论的状态应该在 Postgres 中处于活动状态。

输出:

帖子resultant posts

注意:因为对于帖子 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 ... 

这不完整,但我无法做到这一点。

【问题讨论】:

  • 样本数据和期望的结果会有所帮助。

标签: sql postgresql


【解决方案1】:

在 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;

我认为这与您想要的东西非常相关。

【讨论】:

    【解决方案2】:

    试试这样的:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多