让 排序 按照 in 列表的的显示顺序排序输出。

业务上的稀奇古怪的要求。 必须满足。 

如何 让 sql  查询出来的  数据的排序  是按照   id  在  in ()  列表中的顺序来排序显示呢  ? 

比如 :   select  * from tab  where  id  in  ( 1, 9 , 3,4,  8,5,6) ; 

要按照   1,9,3,48,5,6  的顺序显示数据。 

乍一看, 蒙圈了。 其本质 ,是按照 id  在列表中的位置 来排序。  知道了这个问题 的根本就好办了。 

网上 有现成的   mysql , oracle , sqlserver 的方法。 

mysql写法:

 

SELECT * FROM EVENT WHERE eventId IN(443,419,431,440,420,414,509)  ORDER BY INSTR(',443,419,431,440,420,414,509,',CONCAT(',',eventId,','))

 

oracle写法:

select name from order where oderid in(111,222,333,444,555,666)order by instr('111,222,333,444,555,666',orderid)

 

sqlserver写法:

Select * From Product Where id in (1,1588,15782,9887,54)  Order By charindex(','+ id +',', ',1,1588,15782,9887,54,')

那么PG 数据库的方法呢  ? 

发现pg 真是太牛逼。 我至少能写出 5种方法。 


select * from tab  s(id)
 where id in (17,19,142867, 33) 
 order by position(id::text in '17,19,142867, 33') ;


 select * from tab  where  id  in (17,19,142867, 33)  
order by position(','||id ::text||',' in ','|| '17,19,142867, 33'||',' ) ;


select * from tab 
where id in (17,19,142867, 33)     
 order by  array_positions(array[17,19,142867, 33],id ) ;

select * from tab  s(id)
where id in (17,19,142867, 33)     
 order by  array_positions(‘{17,19,142867, 33}:: array[], id ) ;


select *  from tab 
where  id  = any(array[ 17,19,142867, 33]) 
order  by   array_positions(‘{17,19,142867, 33}:: array[], id ) ; 

前面两种 是基于字符串的构建,  效率上有些慢。 

下面的基于 数值型  数组的方法 ,效率快很多。  


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/133735/viewspace-2284252/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/133735/viewspace-2284252/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值