这是我的问题:
我有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
这会将我的总帖子数量排在最前面(不论用户帖子数量如下),而不是每个用户的帖子数
用户名| user1 | user2 |用户3
total_posts | 11020(总帖数)| NULL | NULL |等等
更多信息:
SELECT created_by, COUNT(*) AS cnt FROM CatA GROUP BY created_by
这让我回报:
created_by | 22 | 26 | 88 | 90个
cnt | 6 | 20 | 15 | 8
答案 0 :(得分:0)
所以看起来每个类别都有一个单独的表(顺便说一下,它实际上不是最优化的设计)。您可以采取哪些措施来获取所有用户的帖子数量:
SELECT u.*,
a.cnt + b.cnt + c.cnt + d.cnt AS total_posts
FROM users u
LEFT JOIN (SELECT user_id, COUNT(*) AS cnt FROM CatA GROUP BY user_id) a
ON u.user_id = a.user_id
LEFT JOIN (SELECT user_id, COUNT(*) AS cnt FROM CatB GROUP BY user_id) b
ON u.user_id = b.user_id
LEFT JOIN (SELECT user_id, COUNT(*) AS cnt FROM CatC GROUP BY user_id) c
ON u.user_id = c.user_id
LEFT JOIN (SELECT user_id, COUNT(*) AS cnt FROM CatD GROUP BY user_id) d
ON u.user_id = d.user_id