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