使用带有LIKE的正则表达式首先对字母表进行排序,然后使用符号SQL

时间:2014-12-27 06:42:35

标签: mysql sql regex select sql-order-by

我有以下MySQL查询

SELECT * FROM `travels`.`destinations` AS `Des`
WHERE `Des`.`name` LIKE '%act%' AND `Des`.`sold` = 'N' AND `Des`.`active` = '1'
GROUP BY `Des`.`name` ORDER BY CASE
WHEN `Des`.`name` REGEX 'act*' THEN 0
WHEN `Des`.`name` LIKE '%act' THEN 1
WHEN `Des`.`name` LIKE '%act%' THEN 2
ELSE 3 END, name LIMIT 10

我想要实现的目标: actabc actzzz abcact zzzact abcactzzz act-act

当我按机制使用这个组时,它首先显示连字符结果,它应该显示。我首先要字母,然后是符号,然后是数字。与外卡的顺序相同。

这些是单独的: How to sort MySQL results with letters first, symbols last? 和 这有点令人困惑(并没有按照我的要求给予小组): mysql regex get position of matched first alphabetic character

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT * 
FROM travels.destinations AS D
WHERE D.name LIKE '%act%' AND D.sold = 'N' AND D.active = '1'
ORDER BY CASE WHEN D.name REGEXP '^[a-zA-Z]*$' AND D.name LIKE 'act%' THEN 0
              WHEN D.name REGEXP '^[a-zA-Z]*$' AND D.name LIKE '%act' THEN 1
              WHEN D.name REGEXP '^[a-zA-Z]*$' AND D.name LIKE '%act%' THEN 2
              ELSE 3 
         END, 
         D.name 
LIMIT 10