you can use the FIELD()
function example
SELECT * FROM mytable
WHERE id IN (2, 5, 1, 6, 4)
ORDER BY FIELD(id, 2, 5, 1, 6, 4);
In this query, we are selecting all rows from mytable
where the id
column matches one of the values in the WHERE IN
clause (2, 5, 1, 6, and 4). We then use the FIELD()
function to order the results based on the sequence of values in the WHERE IN
clause.
Note that the values in the FIELD()
function must match the values in the WHERE IN
clause in both type and order.