Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL specifying exact order with WHERE `id` IN (...)

Is there an easy way to order MySQL results respectively by WHERE id IN (...) clause? Example:

SELECT * FROM articles WHERE articles.id IN (4, 2, 5, 9, 3)

to return

Article with id = 4
Article with id = 2
Article with id = 5
Article with id = 9
Article with id = 3

and also

SELECT * FROM articles WHERE articles.id IN (4, 2, 5, 9, 3) LIMIT 2,2

to return

Article with id = 5
Article with id = 9

Update: to be more specific, I want to avoid tampering with the data in parentheses in WHERE articles.id IN (4, 2, 5, 9, 3), since those IDs are dynamic and automatically ordered.

like image 550
Gray Fox Avatar asked Jun 02 '10 13:06

Gray Fox


People also ask

How do you SELECT ORDER BY specific ids?

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).

Which MySQL clause is used to arrange the data in a particular order?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order.

How do I SELECT specific data in MySQL?

The SELECT query in MySQL offers two options. The first one is to define which tables the command should refer to. You specify the column names after the FROM clause and separate them by commas. The second option is to use the JOIN clause.


2 Answers

Yeah, kind of:

SELECT * FROM articles
WHERE articles.id IN (4, 2, 5, 9, 3)
ORDER BY FIND_IN_SET(articles.id, '4,2,5,9,3')

but this is non-standard SQL and smells a bit.

like image 99
bobince Avatar answered Oct 10 '22 21:10

bobince


This works for me: ORDER BY FIELD(Product.id, 4,9,8,5,3,11,24,16)

like image 34
amstegraf Avatar answered Oct 10 '22 23:10

amstegraf