4

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

示例数据库

+--------+------------+------------+
| 编号 | 1_用户 | 2_用户 |
+--------+------------+------------+
| 1 | 2 | 1 |
| 2 | 3 | 2 |
| 3 | 8 | 7 |
| 4 | 1 | 8 |
| 5 | 2 | 8 |
| 6 | 3 | 8 |  
+--------+------------+------------+

预期结果

用户数
----- -----
8 4
2 3
3 2
1 2
4

4 回答 4

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
于 2012-08-18T09:06:30.883 回答
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
于 2012-08-18T09:02:04.403 回答
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;
于 2012-08-18T09:00:37.990 回答
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
于 2012-08-18T09:13:26.707 回答