【问题标题】:MySQL order by number of substring occurrencesMySQL 按子字符串出现次数排序
【发布时间】:2014-12-12 10:10:57
【问题描述】:

示例表:

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

【问题讨论】:

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


    【解决方案1】:
    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 |
    +----+------------------------+
    

    【讨论】:

    • 看了你的回答终于让我明白了这个错综复杂的问题。
    猜你喜欢
    • 2016-08-16
    • 2014-04-03
    • 2011-10-16
    • 2018-01-21
    • 2021-03-01
    • 2012-08-19
    • 1970-01-01
    • 2010-10-20
    相关资源
    最近更新 更多