计算2个字段中不同值的出现次数

时间:2012-08-18 08:55:53

标签: php mysql

我试图找到一个MySQL查询,它会在特定字段中找到不同的值,计算2个字段(1_user,2_user)中该值的出现次数,然后按计数对结果进行排序。

示例db

+------+-----------+-----------+
|   id | 1_user    | 2_user    |
+------+-----------+-----------+
|    1 |       2   | 1         | 
|    2 |       3   | 2         | 
|    3 |       8   | 7         | 
|    4 |       1   | 8         | 
|    5 |       2   | 8         |
|    6 |       3   | 8         |  
+------+-----------+-----------+

预期结果

user       count
-----      -----
8          4
2          3
3          2
1          2

4 个答案:

答案 0 :(得分:6)

查询

SELECT user, count(*) AS count
FROM
(
    SELECT 1_user AS USER FROM test

    UNION ALL

    SELECT 2_user FROM test
) AS all_users
GROUP BY user
ORDER BY count DESC

<强>解释

列出第一列中的所有用户。

SELECT 1_user AS USER FROM test

将它们与第二列中的用户合并。

UNION ALL
SELECT 2_user FROM test

这里的诀窍是保留重复值的UNION ALL

其余的很简单 - 从子查询中选择所需的结果:

SELECT user, count(*) AS count

按用户汇总:

GROUP BY user

并订明订单:

ORDER BY count DESC

答案 1 :(得分:2)

SELECT u, count(u) AS cnt 
FROM (
    SELECT 1_user AS u FROM table
    UNION ALL
    SELECT 2_user AS u FROM table
) subquery 
GROUP BY u
ORDER by cnt DESC

答案 2 :(得分:1)

进行2次查询:

SELECT COUNT(*) FROM table GROUP BY 1_user

SELECT COUNT(*) FROM table GROUP BY 2_user

现在合并它们:

SELECT user, SUM(count) FROM
  ((SELECT 1_user as user FROM table)
  UNION ALL
  (SELECT 2_user as user FROM table))
GROUP BY user, ORDER BY count DESC;

答案 3 :(得分:0)

我认为您正在寻找的是因为您的预期结果不包括7

select usr, count(usr) cnt from
(
   select user_1 usr from users
   union all
   select user_2 usr from users
) u
where u.usr in (select user_1 from users)
group by usr
order by count(u.usr) desc