SQL WHERE IN (…) sort by order of the list?

谁说我不能喝 提交于 2019-12-18 08:47:11

问题


Let's say I have query a database with a where clause

WHERE _id IN (5,6,424,2)

Is there any way for the returned cursor to be sorted in the order that the _id's where listed in the list? _id attribute from first to last in Cursor to be 5, 6, 424, 2?

This happens to be on Android through a ContentProvider, but that's probably not relevant.


回答1:


Select ID list using subquery and join with it:


select t1.*
from t1
inner join
(
  select 1 as id, 1 as num
  union all select 5, 2
  union all select 3, 3
) ids on t1.id = ids.id
order by ids.num

UPD: Code fixed




回答2:


One approach might be to do separate SQL queries with a UNION between each. You would obviously issue each query in the order you would like it returned to you.




回答3:


... order by
case when _id=5 then 1
when _id=6 then 2
end

etc.




回答4:


You can join it to a virtual table that contains the list required in sort order

select tbl.*
from tbl
inner join (
    select 1 as sorter, 5 as value union all
    select 2, 6 union all
    select 3, 424 union all
    select 4, 2) X on tbl._id = X.value
ORDER BY X.sorter



回答5:


List? You don't have a list! ;)

This:

WHERE _id IN (5,6,424,2)

is mere syntactic sugar for this:

WHERE (
       _id  = 5
       OR _id = 6
       OR _id = 424
       OR _id = 2
      )

SQL has but one data structure, being the table. Your (5,6,424,2) isn't a table either! :)

You could create a table of values but your next problem is that tables do not have any logical ordering. Therefore, as per @cyberkiwi's answer, you'd have to create a column explicitly to model the sort order. And in order to make it explicit to the calling application, ensure you expose this column in the SELECT clause of your query.



来源:https://stackoverflow.com/questions/4858828/sql-where-in-sort-by-order-of-the-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!