hd.
hd.

Reputation: 18306

Select with set order in mysql

I have a query like this:

SELECT title,id FROM table1 WHERE id IN ('2','7','4','10')

The result set is ordered by id by default, but I need it in the exact order of numbers in above set.

How can I achieve this?

Upvotes: 2

Views: 519

Answers (1)

jensgram
jensgram

Reputation: 31508

The FIELD() function should be able to do this:

SELECT
    title, id
FROM
    table1
WHERE
    id IN ('2', '7', '4', '10')
ORDER BY FIELD(id, '2', '7', '4', '10')

See also MySQL sort after argument in IN().

Upvotes: 5

Related Questions