Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL order by the same order of values in IN clause

Tags:

mysql

Here is the simple query with IN clause. But the problem is i need to get the output in the same order of the ids.

SELECT GROUP_CONCAT(username) as users FROM usertable WHERE usr_id IN (54,68,46)

For example if i pass 54,68,46 then the row with usr_id 54 should come first then 68 and then 46 should come. Is there any way to achieve this in MySQL?

like image 642
Stranger Avatar asked Jul 31 '12 06:07

Stranger


2 Answers

We can use FIND_IN_SET on order by clause to get the values in same order like this.

SELECT `username` as users FROM usertable WHERE usr_id IN (54,68,46) ORDER BY FIND_IN_SET(`usr_id`,"54,68,46")

But i don't know how to GROUP_CONCAT in the same order. If anybody gives the answer for that in these kind of simple approach, i can accept that answer.

like image 126
Stranger Avatar answered Oct 14 '22 01:10

Stranger


You need to use ORDER BY clause in GROUP_CONCAT:

SELECT GROUP_CONCAT(username ORDER BY user_id ASC) as users 
FROM usertable 
WHERE usr_id IN (54,68);
like image 38
Omesh Avatar answered Oct 14 '22 00:10

Omesh