tws*_*mes 17 sql sql-server list
我有以下查询返回基于逗号分隔列表的行
Select * from Table where RecordID in (22,15,105,1,65,32)
Run Code Online (Sandbox Code Playgroud)
我希望此查询的结果按列表中ID的顺序返回.这可能与SQL有关吗?
提前致谢
Boh*_*ian 14
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)
Run Code Online (Sandbox Code Playgroud)
Dam*_*ver 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
Run Code Online (Sandbox Code Playgroud)