SQL - order by list order

前端 未结 6 1336
-上瘾入骨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:20

    Use ORDER BY against the RecordID

    Select * from Table where RecordID in (22,15,105,1,65,32) ORDER BY RecordID 
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-11 01:24

    Yes. You add the ORDER BY recordedid clause at the end.

    0 讨论(0)
  • 2020-12-11 01:33
    select * from Table
    where RecordID in (22,15,105,1,65,32)
    order by (
        case RecordID 
            when 22 then 1
            when 15 then 2
            when 105 then 3
            when 1 then 4
            when 65 then 5
            when 32 then 6 end)
    
    0 讨论(0)
  • 2020-12-11 01:33

    The last time I had to do this I ended up doing a union all and generating a select statement for each id, i.e.

    select * from Table where RecordID = 22
    union all
    select * from table where recordid = 15
    

    etc.

    It was a pain but it worked.

    0 讨论(0)
  • 2020-12-11 01:34

    I'd to the ordering in the client, but if you really want to do it in SQL, do it like this:

    declare @T table (id int identity(1,1), RecordID int)
    
    insert into @T (RecordID)
    values (22), (15), (105), (1), (65), (32)
    
    select * from 
    [table] t 
    inner join @t s on t.id=s.recordid
    where t.id in (22, 15, 105, 1, 65, 32)
    order by s.id
    

    (works in SQL Server 2008)

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