Sorting of IN condition values IN MySQL query statements

Source: Internet
Author: User

IN the past, it was very difficult to find out how to sort the values found in. Later, gg and bb found that mysql IN sorting is very simple. Next I will sort out the relevant instances for your reference.

Assume that a table is as follows:

Id Name
1 Zhang San
2 Li Si
3 Wang Wu

When we query multiple data records, the condition is generally a certain range.
For example:>, <, between and, IN

The Code is as follows: Copy code

SELECT * FROM table_name WHERE id IN (2, 1, 3 );


The preceding SQL statement queries data with the id of 2, 1, and 3.
If you just want to query the data, there is no problem.
However, if you want to sort data, you will find that the data found by the SQL statement is as follows:

Id Name
1 Zhang San
2 Li Si
3 Wang Wu

That is to say, it is not sorted by IDS like 2, 1, and 3.

If you want to sort IN order, the SQL statement should be changed to the following:

The Code is as follows: Copy code

SELECT * FROM table_name WHERE id IN (2, 1, 3) order by FIND_IN_SET (id, '2, 1, 3 ')

The result is:

Id Name
2 Li Si
1 Zhang San
3 Wang Wu

This usage can extend a lot...

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.