开发者

How to get Result from database by order the condition put in "IN" clause?

开发者 https://www.devze.com 2023-01-07 10:42 出处:网络
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.

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 Sy开发者_JAVA技巧stem

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...


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


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!)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号