SQL/POSTGRESSQL 试图按值对 2 个不同的表进行分组,然后将它们加入任何想法?

问题描述

我试图从两个不同的表中获取一个新表:转发、喜欢。新表需要包含 post_id、retweet_count 和 likes_count 等列 我尝试使用这样的 sql 查询

SELECT post_id,COUNT(post_id) as retweet_count
FROM retweet
GROUP BY post_id -------> which give me the retweet_count
UNION
SELECT post_id,COUNT(post_id) as likes_count
FROM likes
GROUP BY post_id; -------> which give me the likes_count

我想要得到的结果是这样的:

post_id|retweet_count|likes_count|
1         2            0
2         2            2
3         0            3

我得到的新表只包含 post_id,retweet_count 列,并将 like_count 数据添加为新行而不是新列。

解决方法

您可以join一起使用子查询:

SELECT *
FROM (SELECT post_id,COUNT(post_id) as retweet_count
      FROM retweet
      GROUP BY post_id -------> which give me the retweet_count
     ) r FULL JOIN
     (SELECT post_id,COUNT(post_id) as likes_count
      FROM likes
      GROUP BY post_id -------> which give me the likes_count
     ) l
     USING (post_id);