获取所有列的最常见值

时间:2012-08-28 13:40:52

标签: mysql

我想获取mySQL表中所有列的最常用值。

[id]  [UserID]            [UserID2]
1     johnnietheblack     marywhite
2     johnnietheblack     marywhite
3     dannyrottenegg      dannyrottenegg     
4     marywhite           marywhite
5     marywhite           johnnietheblack     
6     johnnietheblack     marywhite

这是我想要的输出:

[id]  [UserID]            [Count]
    1     johnnietheblack     4
    2     dannyrottenegg      2
    3     marywhite           6

我可以使用以下内容来获取一列的常用值。但是,如何获得所有列的常用值?

SELECT COUNT(*) AS `Rows`, UserID
FROM table-name
GROUP BY UserID
ORDER BY `Rows` DESC

1 个答案:

答案 0 :(得分:2)

SELECT UserID, COUNT(*) FROM
(SELECT UserID FROM tablename
 UNION ALL
 SELECT UserID2 FROM tablename) t
GROUP BY UserID

我没有添加id列,因为它似乎与值无关。

如果要查看每个名称的所有ID,可以使用GROUP_CONCAT:

SELECT GROUP_CONCAT(id), UserID, COUNT(*) FROM
(SELECT id, UserID FROM tablename
 UNION ALL
 SELECT id, UserID2 FROM tablename) t
GROUP BY UserID