Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL order by IN array

Tags:

sql

mysql

I have a MySQL script like this: SELECT id, name FROM users WHERE id IN (6,4,34)

The sequence in the IN(...) array is very important. Is it possible to get them in the given sequence?

like image 427
friction Avatar asked Feb 17 '13 17:02

friction


People also ask

How do I sort an array in MySQL?

Select and Order Data From a MySQL DatabaseThe ORDER BY clause is used to sort the result-set in ascending or descending order. The ORDER BY clause sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

What does ORDER BY mean in MySQL?

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.

In which order is sorting done naturally in MySQL?

There are a whole lot of solutions out there if you hit up Google, and you can, of course, just use the natsort() function in PHP, but it's simple enough to accomplish natural sorting in MySQL: sort by length first, then the column value.


2 Answers

You can use the MySQL FIELD function to keep it compact;

SELECT id, name 
FROM users 
WHERE id IN (6, 4, 34)
ORDER BY FIELD(id, 6, 4, 34);
like image 185
Joachim Isaksson Avatar answered Oct 09 '22 10:10

Joachim Isaksson


Try

SELECT id, name FROM users WHERE id IN (6,4,34) order by FIELD(id,6,4,34)
like image 21
Danylo Mysak Avatar answered Oct 09 '22 11:10

Danylo Mysak