在 SELECT returns 中使用两个 COUNT 相同的值

Using two COUNT in SELECT returns the same values

SELECT user_posts.id, 
   COUNT(user_post_comments.post_id) as number_of_comments,
   COUNT(user_post_reactions.post_id) as number_of_reactions

FROM user_posts

   LEFT JOIN user_post_comments
   ON (user_posts.id = user_post_comments.post_id)

   LEFT JOIN user_post_reactions
   ON (user_posts.id = user_post_reactions.post_id)
WHERE user_posts.user_id = '850e6511-2f30-472d-95a1-59a02308b46a'
group by user_posts.id

我有这个查询是为了从另一个 table post_id

获取评论和反应的数量

current output screenshot

要计算评论和反应的数量,只需使用子查询。无需加入和分组。

SELECT user_posts.id, 
   ( select COUNT(*) from user_post_comments
        where user_posts.id = user_post_comments.post_id
   ) as number_of_comments,
   ( select COUNT(*) from user_post_reactions
        where user_posts.id = user_post_reactions.post_id
   ) as number_of_reactions
FROM user_posts
WHERE user_posts.user_id = '850e6511-2f30-472d-95a1-59a02308b46a'

如果两者都连接 return non-null 行,则每次计数得到的是给定 user_posts.id 中每行的行数的乘积。解决此问题的一种方法是计算每个 table 的不同标识符,例如

COUNT(DISTINCT user_post_comments.id) as number_of_comments

(假设“id”作为 table 上的主键存在)。这可能不是特别有效,但相对简单。