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

后端 未结 5 775
天涯浪人
天涯浪人 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 22:51

    You can add a case construct to your select clause.

    select case when itemid = 9 then 1
    when itemid = 1 then 2 else 3 end sortfield
    etc
    order by sortfield
    
    0 讨论(0)
  • 2020-12-20 22:58

    You could create a procedure to order the data in SQL, but that would be much more complicated than its native language counterpart.

    There's no "neat way" to resort the data like that in SQL -- the WHERE clause of a SELECT simply says "if these criteria are matched, include the row"; it's not (and it cannot be) an ordering criterion.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-20 23:09

    I had the same task once in a mysql environment.

    I ended up using

    ORDER BY FIND_IN_SET(itemID, '9,1,4')

    this is working for me since then. I hope it also works for sqlite

    0 讨论(0)
  • 2020-12-20 23:09

    Use a CASE expression to map the ID values to an increasing sequence:

    ... ORDER BY CASE itemId
                 WHEN 9 THEN 1
                 WHEN 1 THEN 2
                 ELSE        3
                 END
    
    0 讨论(0)
提交回复
热议问题