Reputation:
When I select a set of rows from a table using IN, e.g.
SELECT x.y, x.z FROM x WHERE x.id IN (23, 55, 44, 12)
is there an SQL trick to get them back in the order given in the IN set?
So in the example, assuming x has rows with ids 23, 55, 44 and 12, those four rows would be returned in that order.
Upvotes: 10
Views: 1664
Reputation: 5853
SELECT x.y, x.z FROM x WHERE x.id IN (23, 55, 44, 12)
ORDER BY FIELD (x.id, 23, 55, 44, 12)
Upvotes: 12
Reputation: 455440
You can use FIND_IN_SET as:
SELECT x.y, x.z FROM x WHERE x.id IN (23, 55, 44, 12)
ORDER BY FIND_IN_SET(x.id,'23, 55, 44, 12');
Upvotes: 4