mysql自定义排序第一个alpha然后数字使用大小写时

时间:2010-06-03 20:51:29

标签: mysql

如何使用REGEXP时的ORDER BY CASE对查询进行排序?还是其他选择? 我不想使用UNION。谢谢

mysql> SELECT `floor_id`, `floor_number` FROM `floors`;
+----------+--------------+
| floor_id | floor_number |
+----------+--------------+
|        1 | 4            |
|        2 | 7            |
|        3 | G            |
|        4 | 19           |
|        5 | B            |
|        6 | 3            |
|        7 | A            |
+----------+--------------+


Expected result:
+----------+--------------+
| floor_id | floor_number |
+----------+--------------+
|        7 | A            |
|        5 | B            |
|        3 | G            |
|        6 | 3            |
|        1 | 4            |
|        2 | 7            |
|        4 | 19           |
+----------+--------------+

1 个答案:

答案 0 :(得分:4)

您对REGEXP的使用非常接近。这应该有效:

SELECT floor_id, floor_number FROM floors ORDER BY CASE
WHEN floor_number REGEXP '[a-zA-Z]' THEN 0
ELSE 0+floor_number END ASC, floor_number;

CASE语句将字母排列为0,并使用0+将数字楼层强制转换为可订购的数字值。然后需要按floor_number排序第二级,以便字母顺序排列为A,B,G。如果没有第二级订单,字母地板将被视为等价,其值为0,并且不会按照定义的顺序出现。