Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - SELECT ... WHERE id IN (..) - correct order

Tags:

mysql

I have the following query

SELECT * FROM table WHERE id IN (5,4,3,1,6) 

and i want to retrieve the elements in the order specified in the "id in.." meaning it should return:

5 .... 4 .... 3 .... 1 .... 6 .... 

Any ideas how to do that?

like image 576
Ciprian Mocanu Avatar asked Feb 23 '11 11:02

Ciprian Mocanu


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

How do I select a specific field in MySQL?

If you want to select only specific columns, replace the * with the names of the columns, separated by commas. The following statement selects just the name_id, firstname and lastname fields from the master_name table.

What is id in MySQL?

Authentication ID Each row in the mysql. user table is identified by a user and host tuple. This tuple is the authorization ID. A client can authenticate with an authorization ID and a password. The ID is then referred to as a user or user name.


2 Answers

Use FIELD():

SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD(id, 5,4,3,1,6); 
like image 129
Frank Heikens Avatar answered Sep 28 '22 04:09

Frank Heikens


SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD (id, 5,4,3,1,6) 
like image 33
delphist Avatar answered Sep 28 '22 03:09

delphist