我有3张桌子 - News, Content and Edits
。
每个表格中的每一行都包含一个user_id
字段。
我想要做的是列出这3个表的主要贡献者。
因此,我需要计算每个表中每个不同user_id
出现的次数,并从最高计数到最低计数。
答案 0 :(得分:3)
像这样:
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
答案 1 :(得分:0)
这应该这样做。
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
答案 2 :(得分:0)
这将是每个表的实例
SELECT DISTINCT(COUNT(user_id)) as num FROM news GROUP BY user_id ORDER BY num DESC LIMIT 0,3