Is it possible to specify an arbitrary order for a MySQL SELECT
statement? E.g.,
SELECT * FROM table_name WHERE id IN (1, 3, 2, 9, 7) ORDER BY (1, 3, 2, 9, 7);
The order of the numbers listed directly after IN
do not seem to matter.
The order by the statement is used in SQL to sort the result set in ascending or descending by mentioning it in the suffix as DESC (for descending) and for ASC(for ascending).
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.
The MYSQL ORDER BY Clause is used to sort the records in ascending or descending order.
FIND_IN_SET function will do the trick
SELECT * FROM table_name WHERE id IN (1, 3, 2, 9, 7) ORDER BY FIND_IN_SET(id, '1,3,2,9,7');
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
EDIT: Note the lack of spaces in the string argument of the find_in_set 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