首页 > 解决方案 > MySQL 按计数排序而不对结果进行分组

问题描述

我有以下 MySQL 表:

id| title
1 | Apple
2 | Apple
3 | Cherry
4 | Banana
5 | Banana
6 | Apple

我想按相同字段“标题”的数量对它们进行排序。

所以结果应该是这样的:

1 | Apple
2 | Apple
6 | Apple
4 | Banana
5 | Banana
3 | Cherry

感谢您的帮助

标签: mysqldatabasebackend

解决方案


请参阅下面的查询:

select 
  mt.id, 
  mt.title 
from mytable mt
join (
  select 
    title, 
    count(*) as ct 
  from mytable 
  group by title
) sq on mt.title = sq.title
order by sq.ct DESC, id ASC

并在此处查看演示


推荐阅读