learner
learner

Reputation: 2129

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

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.

Upvotes: 4

Views: 288

Answers (4)

CastroXXL
CastroXXL

Reputation: 161

Could do something with FIND_IN_SET():

SELECT * 
  FROM test 
   JOIN test2 
   ON test.id = test2.id
  WHERE test.id IN (562,553,572)
  ORDER BY FIND_IN_SET(test.id, '562,553,572');

Upvotes: 2

deceze
deceze

Reputation: 522081

You can do this using FIELD():

SELECT ... ORDER BY FIELD(`test`.`id`, 562, 553, 572)

Upvotes: 10

Jonathan Leffler
Jonathan Leffler

Reputation: 753785

One way is like this:

SELECT *
  FROM test JOIN test2 ON test.id=test2.id
 WHERE test.id IN (562,553,572)
 ORDER BY CASE test.id
          WHEN 562 THEN 1
          WHEN 553 THEN 2
          WHEN 572 THEN 3
          ELSE          4
          END;

You don't need GROUP BY unless you are computing aggregates. The ELSE clause is superfluous here, but it is generally a good idea to include it.

Upvotes: 2

a1ex07
a1ex07

Reputation: 37364

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

Upvotes: 2

Related Questions