让sql语句不排序,按照in语句的顺序返回结果

时间:2021-07-20 02:45:00
有时候我们需要按照in条件里的id顺序输出结果,可sql语句在不加order by的时候是按照asc排序的,下边的sql解决按照in条件顺序的id输出查询结果

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,')

 
 分享一个SQL,让in的查询结果按顺序返回结果:SELECT * FROM `pd_customgroup` WHERE `gid` in(2732,2734,2733,99758,2735,109264) order by field(gid, 2732,2734,2733,99758,2735,109264)