tags:

views:

41

answers:

2

Hello

I have the following query (I'm using mysql)

SELECT * FROM campaigns where campaign_id IN ( 'idStrOne', 'idStrTwo', 'idStrThree' );

The results of which are being ordered by the primary key of the table campaigns which is 'id'. This is not the order I want.

I want the results to come back in the same order as the arguments to the IN function. So in this case the order I want is

idStrOne, idStrTwo, idStrThree

How do I get this order ?

+1  A: 

You could try adding a CASE expression in the ORDER BY Clause

SELECT * 
FROM campaigns 
WHERE campaign_id IN ( 'idStrOne', 'idStrTwo', 'idStrThree' )
ORDER BY 
(CASE campaign_id WHEN 'idStrOne' THEN 1 WHEN 'idStrTwo' THEN 2 ELSE 3 END);
Tim C
+1 love the case statement in the order by. Use it all the time, such a valuable tool!
northpole
A: 

Duplicated See here: http://stackoverflow.com/questions/396748/ordering-by-the-order-of-values-in-a-sql-in-clause

Burnsys
a little different
TStamper