MySQL按子串出现次数排序

时间:2014-10-16 21:59:51

标签: mysql group-by sql-order-by substring

示例表:

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

我需要按照下降的数量来订购它,而不是看颜色。我知道桌子本来可以分为水果和颜色,但这是另一个故事。

结果应该是这样的,按子串的数量排序,"在第一个之前的所有内容:"

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中进行排序?

1 个答案:

答案 0 :(得分:2)

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 |
+----+------------------------+