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.