Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I order a query result same as the id specified in the WHERE condition?

Tags:

php

mysql

I have a query like this

SELECT *
  FROM test JOIN test2 ON test.id=test2.id
 WHERE test.id IN (562,553,572)
 GROUP BY test.id

Its results are ordered like this: 553, 562, 572...

But I need the same order that I specified in the IN(562,553,572) condition.

like image 290
learner Avatar asked Dec 06 '22 01:12

learner


2 Answers

You can do this using FIELD():

SELECT ... ORDER BY FIELD(`test`.`id`, 562, 553, 572)
like image 154
deceze Avatar answered Dec 08 '22 01:12

deceze


ORDER BY CASE test.id WHEN 562 THEN 0 WHEN 553 THEN 1 WHEN 572 THEN 2 END

like image 22
a1ex07 Avatar answered Dec 08 '22 01:12

a1ex07