【问题标题】:Sort order on matching starting letters in words单词中匹配起始字母的排序顺序
【发布时间】:2015-11-10 00:18:57
【问题描述】:

我有一张表,我正在尝试在 name 上使用“apple m”过滤值

select * from table where name like '%apple%m%'
+-------+-------------------------------+------------------------+
|  id   |             name              |          cat           |
+-------+-------------------------------+------------------------+
|  2757 | Apple MacBook                 | Laptops & Accessories  |
|  2777 | Apple Bottom Tops             | Western Wear           |
|  2752 | Apple Monitors                | Desktop Components     |
|  2756 | Apple Desktop & Monitors      | Desktops & Accessories |
|  2778 | Apple Bottom Tunics           | Tops                   |
|  2776 | Apple Selector & Smart Box    | Video & TV Accessories |
|  2787 | Apple Pie Pyjamas             | Girl Clothes           |
|  2773 | Apple Selector & Smart Box    | TV & Video Accessories |
|  2780 | Apple Fun Card Games          | Toys                   |
| 38304 | Snapple Mixer juicer grinders | Kitchen Appliances     |
+-------+-------------------------------+------------------------+

我想对以“apple”和“m”开头的显示值进行排序,如下所示:

+------+--------------------------+------------------------+
|  id  |           name           |          cat           |
+------+--------------------------+------------------------+
| 2757 | Apple MacBook            | Laptops & Accessories  |
| 2752 | Apple Monitors           | Desktop Components     |
| 2756 | Apple Desktop & Monitors | Desktops & Accessories |
|      | ---Rest all after this-- |                        |
+------+--------------------------+------------------------+

【问题讨论】:

  • 为什么Apple Monitors后面有Apple DesktopD 位于 M 之前。

标签: mysql mysql-workbench


【解决方案1】:

用途:

ORDER BY name LIKE 'Apple%m%' DESC, name ASC

name LIKE 'Apple%m%'1 当名称匹配模式时,0 当它不匹配时,所以这将首先排序匹配的名称。然后它将按每个组中的名称排序。

【讨论】:

    【解决方案2】:

    我认为您可以使用以下简单的方法:

    SELECT * FROM your_table WHERE name LIKE 'apple% m%' ORDER BY name;
    

    上述查询首先会获取名称以'apple ' 开头的行,然后对结果进行排序。

    如果您需要区分大小写,则可以使用:

    SELECT * FROM your_table WHERE name LIKE 'Apple% m%' COLLATE utf8_bin ORDER BY name;
    

    Case sensitivity in like

    【讨论】:

    • 嗨 Kostas,如果我按名称订购,它将首先列出“Apple Bottom Tops”和“Apple Bottom Tunics”
    • 哦,在您的预期结果中,您有:Apple 桌面和显示器,因此我认为您想要那个。
    • 您的意思是说您只想要一个单词是“Apple”而其他单词以“m”开头的结果吗?
    猜你喜欢
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 2018-07-13
    相关资源
    最近更新 更多