mysql:ORDER BY mysql表列中元素的出现次数

时间:2014-10-03 21:26:12

标签: mysql phpmyadmin

根据编号,有人可以帮我'订购'一个mysql表。在同一个表的一列中出现的字符串。

我想根据位置发生的次数重新排列表格。

请参阅以下示例:

id    name       location
--    -----      --------
1     Mark       US
2     Mike       US
3     Paul       Australia
4     Pranshu    India
5     Pranav     India
6     John       Canada
7     Rishab     India

预期结果:

id    name       location
--    -----      --------
4     Pranshu    India
5     Pranav     India
7     Rishab     India
1     Mark       US
2     Mike       US
3     Paul       Australia
6     John       Canada

我尝试了这个查询:

SELECT *, COUNT(location) AS count FROM `tablename` GROUP BY `location` ORDER BY count DESC;

但是它向我展示了以下结果忽略位置的重复出现

id    name       location
--    -----      --------
4     Pranshu    India
1     Mark       US
3     Paul       Australia
6     John       Canada

1 个答案:

答案 0 :(得分:3)

SELECT x.* 
  FROM my_table x 
  JOIN (SELECT location, COUNT(*) total FROM my_table GROUP BY location) y
    ON y.location = x.location
 ORDER 
    BY total DESC
     , id;