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

后端 未结 5 1331
一生所求
一生所求 2020-12-21 03:27

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 th

相关标签:
5条回答
  • 2020-12-21 04:04

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

    etc.

    0 讨论(0)
  • 2020-12-21 04:05

    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.

    0 讨论(0)
  • 2020-12-21 04:13

    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
    
    0 讨论(0)
  • 2020-12-21 04:25

    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.

    0 讨论(0)
  • 2020-12-21 04:26

    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

    0 讨论(0)
提交回复
热议问题