示例表:
ID Name
1 Apple: Color: Yellow
2 Apple: Color: Red
3 Grapes: Color: Green
4 Grapes: Color: Green
5 Oranges: Color: Orange
6 Apple: Color: Yellow
7 Apple: Color: Yellow
我需要按水果数量降序排列,而不看颜色。我知道 table 可能会根据水果和颜色进行划分,但那是另一回事了。
结果应该是这样的,按子字符串的计数排序,“第一个之前的所有内容:”
ID Name
1 Apple: Color: Yellow
2 Apple: Color: Red
6 Apple: Color: Yellow
7 Apple: Color: Yellow
3 Grapes: Color: Green
4 Grapes: Color: Green
5 Oranges: Color: Orange
是否可以在 mysql 中进行排序,还是需要在 PHP f.ex 中进行排序?
最佳答案
mysql> SELECT e.* FROM example AS e
JOIN (
SELECT SUBSTRING_INDEX(name, ':', 1) AS fruit, count(*) AS count
FROM example
GROUP BY fruit) AS x
ON SUBSTRING_INDEX(e.name, ':', 1) = x.fruit
ORDER BY x.count DESC, e.id;
+----+------------------------+
| id | name |
+----+------------------------+
| 1 | Apple: Color: Yellow |
| 2 | Apple: Color: Red |
| 6 | Apple: Color: Yellow |
| 7 | Apple: Color: Yellow |
| 3 | Grapes: Color: Green |
| 4 | Grapes: Color: Green |
| 5 | Oranges: Color: Orange |
+----+------------------------+
关于MySQL 按子字符串出现次数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26414637/