简体   繁体   中英

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

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 returned in the order that I specified in the array.

I know I could reorder them after in my native language (obj c), but is there a neat way to do this in SQL?

Somthing like this would be great:

ORDER BY itemId (9,1,4) --    <-- this dosn't work :)

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

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM