SQL - order by list order

前端 未结 6 1362
-上瘾入骨i
-上瘾入骨i 2020-12-11 00:38

I have the following query that returns rows based on a comma seperated list

Select * from Table where RecordID in (22,15,105,1,65,32)

I wo

6条回答
  •  遥遥无期
    2020-12-11 01:24

    If you need the output to appear in a particular order, then you need to specify that order, using something the server can sort. Not knowing which engine you're working against, the general scheme would be to create a temp table or use rowset constructors to pair each record ID with its desired sort order.

    E.g. (SQL Server)

    declare @T table (RecordID int,Position int)
    insert into @T (RecordID,Position)
    select 22,1 union all
    select 15,2 union all
    select 105,3 union all
    select 1,4 union all
    select 65,5 union all
    select 32,6
    
    select * from Table t inner join @T t2 on t.RecordID = t2.RecordID order by t2.Position
    

提交回复
热议问题