views:

76

answers:

2

Possible Duplicate:
Ordering by the order of values in a SQL IN() clause

With a query such as:

SELECT * FROM images WHERE id IN (12,9,15,3,1)

is it possible to order the results by the contents of the IN clause?

The result I'm looking for would be something like:

[0] => Array
    (
        [id] => 12
        [file_name] => foo
    )   
[1] => Array
    (
        [id] => 9
        [file_name] => bar
    )   
[2] => Array
    (
        [id] => 15
        [file_name] => baz
    )
...
+4  A: 

The IN clause defines a set, and a set in mathematics has no order.

However there seems to be a workaround for MySQL by using the FIELD() function:

Daniel Vassallo
Yes it is possible by tweaking the SQL query. See here: http://stackoverflow.com/questions/396748/ordering-by-the-order-of-values-in-a-sql-in-clause
Felix Kling
@Felix: Thanks for the tip. Modified my answer to make it more accurate.
Daniel Vassallo
Awesome, thank you!
Deca
A: 
select * from images
where id in (12,9,15,3,1)
order by
    case
        id when 12 then 1
        when 9 then 2
        when 15 then 3
        when 3 then 4
        when 1 then 5
    end
Ergec