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
)
...
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 .
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With