views:

58

answers:

3

Sorry for bad english.

bfproduct is a table and productid is primary key in this table and productname is another field defined in this table.

When i execute this query, select * from bfproduct where productid in (23,5,54,3132,32). The result is as follows:

 

productid | productname

5         15 Park Avenue
23        Good Boy Bad Boy
32        dsf sf gfdsf dsf d  
54       dsdsfsa ffs ff sfsf 
3132        Just Books - On The Failure of Legal System

Is there any way i will get the resultset in the order by the productid provided in "IN" Clause e.g.


productid | productname
23        Good Boy Bad Boy
5         15 Park Avenue
54       dsdsfsa ffs ff sfsf 
3132        Just Books - On The Failure of Legal System
32        dsf sf gfdsf dsf d  

Please help...

A: 

You have to add a ORDER BY clause that puts the rows to correct order.

Juha Syrjälä
@juha: Can you please provide me any example
Shashi Bhushan
See http://stackoverflow.com/questions/3228027/how-to-get-result-from-database-by-order-the-condition-put-in-in-clause/3228064#3228064
Juha Syrjälä
+10  A: 

Here's one way to do it:

SELECT *
FROM bfproduct
WHERE productid
IN (23,5,54,3132,32)
ORDER BY
   CASE productid
      WHEN   23 THEN 0
      WHEN    5 THEN 1
      WHEN   54 THEN 2
      WHEN 3132 THEN 3
      WHEN   32 THEN 4
   END
Mark Byers
This is great for a one time use, but in my opinion, the other solution would be better for building a reusable solution.
Jeff
+1  A: 

First thing I can think of, try something like...

select  bfproduct.*
from    bfproduct INNER JOIN
(
    select 1 as sequence, 23 as productid
    union
    select 2,5
    union
    select 3,54
    union
    select 4,3132
    union
    select 5,32
) as lookup on bfproduct.productid=lookup.productid
order by lookup.sequence

(I havent tested this so maybe some minor syntax errors!)

barrylloyd
this is is similar idea to mark byers answer above (which I have voted up as I thinks its more elegant)
barrylloyd
The nice thing about this solution is that you only have to specify the order you want and the key field once. This also lends the solution to being reusable. For the other solution you would need to create both your sort and where clause each time you create a new report.
Jeff
And of course in this case UNION ALL is far more appropriate than UNION
HLGEM