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.
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 MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order.
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.
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.
This works for me: ORDER BY FIELD(Product.id, 4,9,8,5,3,11,24,16)
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