MySQL query results sorted in specified order

Source: Internet
Author: User
Tags mysql query

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.