How to sort Mysql select in by id

Source: Internet
Author: User

The table structure is as follows:
Mysql> select * from test;
+ ---- + ------- +
| Id | name |
+ ---- + ------- +
| 1 | test1 |
| 2 | test2 |
| 3 | test3 |
| 4 | test4 |
| 5 | test5 |
+ ---- + ------- +

Run 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 results of this select statement in mysql are automatically sorted in ascending order of IDs,
However, if I want to execute "select * from test where id in (, 5);", the results are sorted by the conditions in, that is, 3, 1, 5,

The expected result is as follows:
Id name
3 test3
1 test1
5 test5

How can I write such SQL statements in Mysql?
If SQL Server is found online, order by charindex can be used, but Mysql cannot be found, how can this problem be solved ?? Thank you for your help.

Thank you!

Select * from a order by substring_index ('3, 1, 2 ', id, 1 );

Try this good, ls positive solution.


Order by find_in_set (id, '3, 1, 5 ')

Thank you. You can test order by substring_index and order by find_in_set.

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.