MySQL This function is very useful!!
To sort the results of a query in the specified order
----------------------------------------------------------------------
The table structure is as follows:
Mysql> SELECT * from Test;
+----+-------+
| ID | name |
+----+-------+
| 1 | Test1 |
| 2 | Test2 |
| 3 | Test3 |
| 4 | test4 |
| 5 | Test5 |
+----+-------+
Execute the following sql:
Mysql> SELECT * from test where ID in (3,1,5);
+----+-------+
| ID | name |
+----+-------+
| 1 | Test1 |
| 3 | Test3 |
| 5 | Test5 |
+----+-------+
3 Rows in Set (0.00 sec)
The result of this select in MySQL is automatically sorted by ID in ascending order,
But I want to execute "SELECT * from Test where ID in (3,1,5);" The results are sorted according to in criteria, i.e.: 3,1,5, the desired result is as follows:
ID Name
3 Test3
1 test1
5 TEST5
Here's how:
SELECT * from test where ID in (3,1,5) Order by Find_in_set (ID, ' 3,1,5 ');
SELECT * from test where ID in (3,1,5) Order by Substring_index (' 3,1,2 ', id,1);
MySQL query results sorted in specified order