按大多数常用值排序mysql结果

时间:2013-04-29 17:08:25

标签: mysql

有没有办法根据值在mysql列中显示的频率来排序数据,并使它们成为DISTINCT。因此,如果表中有一个颜色列,如下所示:

colors
------ ----
red   |
blue  | 
red   |
green |
blue  |
red   |
yellow|
blue  |
green |
red   |

结果将是:

red
blue
green
yellow
红色出现4次,蓝色3次绿色两次,黄色一次。感谢

2 个答案:

答案 0 :(得分:4)

您需要分组您的记录,然后按合适的aggregate function排序:

SELECT colors FROM my_table GROUP BY colors ORDER BY COUNT(*) DESC

sqlfiddle上查看。

答案 1 :(得分:1)

使用分组/计数查询:

SELECT color, count(color) AS cnt
FROM colors
GROUP BY color
ORDER BY cnt DESC