这是我的问题:我有 4 个表,其中包含用户完成的帖子(例如 CatA、CatB、CatC 和 CatD,每个表都包含 created_by 列)。我的要求是从表中获取所有可用的用户USER
以及帖子计数(帖子的总和)。
我正在努力寻找过去 2 天的答案,但我仍然一无所知。
任何想法都非常感谢。
SELECT u.username,
a.cnt + b.cnt + c.cnt + d.cnt AS total_posts
FROM users u
LEFT JOIN (SELECT created_by, COUNT(*) AS cnt FROM CatA GROUP BY created_by) a
ON u.id = a.created_by
LEFT JOIN (SELECT created_by, COUNT(*) AS cnt FROM CatB GROUP BY created_by) b
ON u.id = b.created_by
LEFT JOIN (SELECT created_by, COUNT(*) AS cnt FROM CatC GROUP BY created_by) c
ON u.id = c.created_by
LEFT JOIN (SELECT created_by, COUNT(*) AS cnt FROM CatD GROUP BY created_by) d
ON u.id = d.created_by
ORDER BY total_posts DESC
这会返回我在顶部的总帖子数(与用户帖子数无关),如下所示,而不是每个用户的帖子数
用户名 | 用户1 | 用户2 | 用户 3 总帖子
| 11020(帖子总数)| 空 | 空 | 等等
更多信息:
SELECT created_by, COUNT(*) AS cnt FROM CatA GROUP BY created_by
这让我回想起:
created_by | 22 | 26 | 88 | 90
厘米 | 6 | 20 | 15 | 8