user213154
user213154

Reputation:

Ordering MySQL results by IN sequence?

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

Answers (2)

Steve
Steve

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

codaddict
codaddict

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

Related Questions