我正在尝试将使用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;
答案 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;