Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

sqlite - 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 :)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...