Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to manually select order in mysql query?

i have table:

table1
------------
id  |  name
------------
1   |  John
2   |  Steeve
3   |  Walter
4   |  Daniel
5   |  Jeremy
6   |  Carmelo
...

What i need is to select from table in order i manually enter e.g. id 5,3,6,1,4,2

SELECT * FROM talbe1 ORDER BY (5,3,6,1,4,2)

Is it possible somehow? Thanks!

like image 495
woopata Avatar asked Mar 05 '12 12:03

woopata


People also ask

How do I sort a MySQL query?

The MySQL ORDER BY Keyword 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. To sort the records in descending order, use the DESC keyword.

Can you query columns in any order?

The order doesn't matter, actually, so you are free to order them however you'd like. edit: I guess a bit more background is helpful: As far as I know, the process of optimizing any query happens prior to determining exactly what subset of the row data is being pulled.


2 Answers

You can use ORDER BY FIELD:

SELECT * FROM talbe1 ORDER BY FIELD(id, 5,3,6,1,4,2)
like image 158
Mark Byers Avatar answered Oct 13 '22 22:10

Mark Byers


You can probably try this:

SELECT * FROM talbe1 ORDER BY FIELD(id,'5','3','6','1','4','2')
like image 28
Rahul Avatar answered Oct 13 '22 23:10

Rahul