Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With a SELECT...WHERE id IN (...), order results by IN()? [duplicate]

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
    )
...
like image 586
Jeff Avatar asked Mar 12 '10 21:03

Jeff


People also ask

How do you get query results in the same order as given in clause?

in php u can do it like : <? php $my_array = array (3,6,1,8,9) ; $sql = 'SELECT * FROM table WHERE id IN (3,6,1,8,9)'; $sql .

How do I get records in the same order in SQL?

The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Can we use ORDER BY with WHERE clause in SQL?

You can use the WHERE clause with or without the ORDER BY statement. You can filter records by finite values, comparison values or with sub-SELECT statements.

Does SELECT return in order?

By default, SELECT returns rows in no particular order. The ORDER BY clause returns the rows in a given sort order. Rows can be returned in ascending or descending sort order.


1 Answers

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:

  • Ordering by the order of values in a SQL IN() clause
like image 85
Daniel Vassallo Avatar answered Sep 22 '22 23:09

Daniel Vassallo