Problem:
When using the WHERE IN clause, the rows are typically ordered ascendingly by the column specified in the ORDER BY clause. However, there are scenarios where it is desired to maintain the order of rows as specified in the IN clause.
Solution:
To achieve this, you can employ the ORDER BY FIELD function. This function reorders the rows based on the specified order in its arguments.
Example:
Consider the following query:
SELECT * FROM table WHERE id IN (118, 17, 113, 23, 72);
This query will return the rows ordered by id ascendingly. To preserve the order of rows as specified in the IN clause, you can use the following modified query:
SELECT * FROM table WHERE id IN (118, 17, 113, 23, 72) ORDER BY FIELD(id, 118, 17, 113, 23, 72)
By specifying the desired order as arguments to the FIELD function, the rows will be reordered to match that order.
The above is the detailed content of How Can I Preserve Row Order in Conditional Queries Using `WHERE IN` Clause?. For more information, please follow other related articles on the PHP Chinese website!