SQL - 按列表顺序排序

18

我有以下查询,根据逗号分隔的列表返回行

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

我希望通过SQL查询结果按照列表中ID的顺序返回。这是否可行?

提前感谢。


你需要哪种SQL数据库系统,还是需要一些可移植的东西? - Damien_The_Unbeliever
6个回答

16
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)

1
recordId将会是一个动态列表(忘记提到这一点了)。 - twsJames
@twsJames- 由于你的语句看起来像这样 in (22,15,105,1,65,32),所以你已经在动态构建查询,因此最好同时构建 order by。如果没有,你如何为具有动态值列表的查询参数化呢? - Mikael Eriksson
到目前为止最佳答案 - biko

10
如果您需要结果以特定的顺序呈现,则需要使用服务器可以排序的内容来指定排序方式。不知道您正在使用哪个引擎,通常的方案是创建一个临时表或使用行集构造函数将每个记录ID与其所需的排序顺序配对。
例如(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

非常感谢,运行得很好。 - twsJames

3

如果您真的想在SQL中进行排序,可以按照以下方式操作:

我会在客户端进行排序,但是如果您确实想在SQL中进行排序,请按照以下步骤操作:

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

(适用于SQL Server 2008)


我无法找到任何关于插入语句中表值构造函数中行的顺序是否会与IDENTITY值分配有关的文档。这让我感到不安。 - Damien_The_Unbeliever
很受尊重。否则,您总是可以逐个完成。 - Jonas Lincoln
使用这个解决方案,您不需要 where t.id in (22, 15, 105, 1, 65, 32) - lanierhall

0

是的。您可以在末尾添加ORDER BY recordedid子句。


3
我认为你没有理解:他希望查询结果与查询时的顺序完全一致。 - Bohemian

-1
上次我做这个的时候,最终我使用了 union all 并为每个 id 生成了一个 select 语句。
select * from Table where RecordID = 22
union all
select * from table where recordid = 15

等等。

虽然很痛苦,但它起作用了。


1
UNIONUNION ALL没有排序保证 - 引擎可以自由地以其认为最有效的顺序返回结果。这可能会偶然以请求的顺序返回结果,但任何事情(主要版本更改、服务包、热修复、服务器工作负载、时间、月相、衬衫颜色)都可能意味着结果以另一种顺序返回。 - Damien_The_Unbeliever
要做到这一点,您需要为每个SELECT添加一个顺序值,例如SELECT [rank] = 1, * FROM Table WHERE ... UNION ALL SELECT [rank] = 2, * FROM Table WHERE ... ORDER BY [rank]。当然,这可能会变得非常昂贵,具体取决于WHERE子句中可能需要放入的其他内容,更不用说是否需要连接其他表了,因此我绝对不赞成这种方法。它有几个痛点。 - Aaron Bertrand
好的,看起来我只是在做的时候走了狗屎运。 - DoctorMick

-3

使用ORDER BYRecordID进行排序

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

嗨,塔尔哈,我希望记录按照列表中的顺序排序。例如,记录1 = id 22,记录2 = id 15等。这可能吗? - twsJames

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接