How do I preserve the order of a SQL query using the IN command

后端 未结 5 804
天涯浪人
天涯浪人 2020-12-20 22:47
SELECT * FROM tblItems
WHERE itemId IN (9,1,4)

Returns in the order that SQL finds them in (which happens to be 1, 4, 9) however, I want them retur

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-20 23:09

    Probably the best way to do this is create a table of item IDs, which also includes a rank order. Then you can join and sort by the rank order.

    Create a table like this:

     itemID rank
     9      1
     1      2
     4      3
    

    Then your query would look like this:

    select tblItems.* from tblItems
        inner join items_to_get on
            items_to_get.itemID = tblItems.itemID
        order by rank
    

提交回复
热议问题