一条SQL语句研究

现有“select * from t where a in (5,3,2,1,8,9,30...)" 假设 a 是主键,in里面的参数是唯一的。现要求输出的结果集按照 in 提供的参数顺序排序。而不是按照a本身的排序规则排序?   。

另:如果不要求使用临时表或表变量,那么又有什么办法实现。?

临时表方案参卡:

create table #t(id int identity(1,1),a int)

insert into #t values(5)

insert into #t values(3)

insert into #t values(2)

insert into #t values(1)

insert into #t values(8)

insert into #t values(9)

insert into #t values(30)

select t.* from t,#t as t1 where t.a=t1.a order by t1.id

如果不用临时表:(该方法极度不推荐,N倍的扫描全表时间)
select * from t where a=5 union all
select * from t where a=3 union all
select * from t where a=2 union all
select * from t where a=1 union all
select * from t where a=8 union all
select * from t where a=9 union all
select * from t where a=30
 

 

 

猜你喜欢

转载自blog.csdn.net/zj53hao/article/details/2595333