[英]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. 以SQL查找它们的顺序返回(恰好是1、4、9),但是,我希望它们以我在数组中指定的顺序返回。
I know I could reorder them after in my native language (obj c), but is there a neat way to do this in SQL? 我知道以后可以使用本机语言(obj c)对它们进行重新排序,但是在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. 可能最好的方法是创建一个项目ID表,其中还包括一个排名顺序。 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: 使用CASE表达式将ID值映射到递增的序列:
... 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. 您可以将case构造添加到select子句中。
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. 我曾经在mysql环境中执行过相同的任务。
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 我希望它也适用于sqlite
You could create a procedure to order the data in SQL, but that would be much more complicated than its native language counterpart. 您可以创建一个过程来对SQL中的数据进行排序,但这将比其本国语言复杂得多。
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"; 有没有“整洁的方式”诉诸于SQL这样的数据-在WHERE
一个子句SELECT
简单地说,“如果这些标准都匹配,包括行”; it's not (and it cannot be) an ordering criterion. 它不是(也不能是)订购标准。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.