如何使用 IN 命令保留 SQL 查询的顺序 [英] How do I preserve the order of a SQL query using the IN command
本文介绍了如何使用 IN 命令保留 SQL 查询的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
SELECT * FROM tblItems
WHERE itemId IN (9,1,4)
按照 SQL 找到它们的顺序返回(恰好是 1、4、9)但是,我希望它们按照我在数组中指定的顺序返回.
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.
我知道我可以用我的母语 (obj c) 对它们重新排序,但是在 SQL 中是否有一种巧妙的方法可以做到这一点?
I know I could reorder them after in my native language (obj c), but is there a neat way to do this in SQL?
这样的事情会很棒:
ORDER BY itemId (9,1,4) -- <-- this dosn't work :)
推荐答案
可能最好的方法是创建一个项目 ID 表,其中还包括一个排名顺序.然后就可以按照排名顺序加入排序了.
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.
像这样创建一个表:
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
这篇关于如何使用 IN 命令保留 SQL 查询的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文