Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get query result in same order as given in clause [duplicate]

Tags:

php

mysql

I have a table like below, id being the primary key

      ID Name
      1  a
      2  b
      3  c
      4  d
      5  e 

and have a query like below. This query is created in a php file from user input choices.

    select name from table where id in (1,5,3)

I get the result ("a", "c", "e") which I guess is normal because of the default primary key sort order. However I want result to be ordered in the same sequence as the "in" clause. So I want returned value to be ("a", "e", "c"). Is there any way to get it in mysql.

like image 865
John Avatar asked Aug 30 '25 16:08

John


1 Answers

You can simply use FIELD():

select name from TableName where id in (1,5,3)
ORDER BY field(id,1,5,3)

Result:

NAME
a
e
c

See result in SQL Fiddle.

like image 184
Raging Bull Avatar answered Sep 02 '25 07:09

Raging Bull