将2个结果集的结果与通用属性mySQL合并

时间:2018-10-07 09:48:18

标签: mysql database join select

我正在尝试将使用SQL查询获得的两个结果集组合到一个结果集中。集合各有2列。第一组包含昵称和帖子,而另一组是昵称和评论。如何将这两个集合结合起来显示每个昵称有多少帖子和评论?最终结果集应包含:昵称,帖子,评论。

第一组:

SELECT u.nickname, COUNT(c.nickname) AS comments 
 FROM postcomments c, users u WHERE c.nickname = u.nickname 
GROUP BY nickname;

第二组:

SELECT u.nickname, COUNT(*) AS posts 
 FROM postauthors a, users u WHERE a.nickname = u.nickname 
GROUP BY u.nickname;

1 个答案:

答案 0 :(得分:1)

您可以使用JOIN来完成

SELECT u.nickname, COUNT(c.id) AS comments,count(a.id) AS posts 
 FROM users u
 LEFT JOIN postcomments c ON c.nickname = u.nickname
 LEFT JOIN postauthors a ON a.nickname=u.nickname
GROUP BY u.nickname;