Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return query results in same order as the values in my `IN(....)` statement

Tags:

sql

mysql

I need to select users from my database with the "IN" statement like:

SELECT *
FROM users
WHERE user_id IN ("20,24,23,26,27,28,25")

...this works but i need exactly this order (20,24,23,26,27,28,25) for my output. PHP orders the ids by DESC or ASC ... how can i solve this problem?

like image 374
Jim Avatar asked Jan 14 '23 10:01

Jim


1 Answers

just use FIELD() in the ORDER BY clause

ORDER BY FIELD(user_id, 20, 24, 23, 26, 27, 28, 25) ASC
  • MySQL FIELD()
like image 145
John Woo Avatar answered Jan 19 '23 12:01

John Woo