MySQL sorting by the custom list of specified fields, mysql Field

Source: Internet
Author: User

MySQL sorting by the custom list of specified fields, mysql Field

Problem description

As we all know, the SQL statements in the ascending order of a field in MySQL are (taking id as an example, the same below ):

SELECT * FROM 'mytable'
WHERE 'id' IN (1, 7, 3, 5)
Order by 'id' ASC

The SQL statements in descending order are:

SELECT * FROM 'mytable'
WHERE 'id' IN (1, 7, 3, 5)
Order by 'id' DESC

Sometimes the above sorting does not meet our needs. For example, how do we arrange IDs in the order of 5, 3, 7, and 1. This is also one of the problems that many domestic and foreign counterparts often encounter.

Next we will provide a solution to sort by a field in the table in the list we want.

Solution

Sort by field (order by field ).

Syntax

Order by field ('id', 5, 3, 7, 1)

Note that there is no space behind the FIELD.

Therefore, the complete SQL statement is:

SELECT * FROM 'mytable'
WHERE 'id' IN (1, 7, 3, 5)
Order by field ('id', 5, 3, 7, 1)

Common applications

SELECT * FROM 'mytable'
WHERE 'name' IN ('zhang san', 'Li si', 'wang wu', 'Sun liu ')
Order by field ('name', 'Lee 4', 'Sun 6', 'zhang san', 'wang wu ')

The above implementation of sorting by the custom list of specified fields in MySQL is all the content shared by the editor. I hope to give you a reference and support for the customer's house.

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.