How can you sort a query using ORDER BY CASE WHEN REGEXP? or other alternatives?
I don’t want to use UNION. Thank you
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 |
+----------+--------------+
Your use of REGEXP is pretty close. This should work:
The
CASEstatement ranks the lettered floors as0and uses0+to coerce the numeric floors into a number value that can be ordered. A second level sort byfloor_numberis then required so that the lettered floors order correctly as A,B,G. Without the 2nd level order the lettered floors would all be considered equivalent with a value of0and would not appear in a defined order.