Using FIELD Function to Order Results by IN() Order
In MySQL, the ORDER BY clause can be used to sort query results in ascending or descending order. When using the IN() method, it can be difficult to ensure that the results are returned in the same order as the IDs in the IN() clause. Fortunately, there is a solution: the FIELD function.
The FIELD function takes two parameters: a field name and a list of values. It returns the index of the first value in the list that matches the field value. For example, the following query would return the values 1, 2, 3, for the column "id" for rows where the value is 3, 2, or 1:
SELECT id, FIELD(id, 3, 2, 1) AS ordering FROM table_name;
To order the results by the IN() order, simply pass the IN() clause values as the second parameter to the FIELD function:
SELECT id, FIELD(id, 4, 7, 3, 8, 9) AS ordering FROM table_name;
This will return the results in the order specified:
4 - Article 4 7 - Article 7 3 - Article 3 8 - Article 8 9 - Article 9
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3