我有 3 张桌子 - News, Content and Edits
。
每个表中的每一行都包含一个user_id
字段。
我想做的是列出这 3 个表的主要贡献者。
所以我需要计算user_id
每个表中每个不同出现的次数,并从最高计数到最低计数。
像这样:
SELECT
user_id,
COUNT(*) AS all_actions
FROM (
SELECT user_id FROM News
UNION ALL
SELECT user_id FROM Content
UNION ALL
SELECT user_id FROM Edits
) tmp_table
GROUP BY user_id
ORDER BY all_actions DESC
这应该这样做。
SELECT all_user_ids.user_id as `user_id`, COUNT(all_user_ids.user_id) as `count`
FROM
(SELECT user_id FROM news
UNION ALL
SELECT user_id FROM content
UNION ALL
SELECT user_id FROM edits) AS all_user_ids
GROUP BY `user_id`
ORDER BY `count` DESC
这将是每个表的实例
SELECT DISTINCT(COUNT(user_id)) as num FROM news GROUP BY user_id ORDER BY num DESC LIMIT 0,3