-3

这是我的问题:我有 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

4

1 回答 1

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
于 2012-08-20T18:25:02.353 回答