mysql order by in 的字符顺序

select id from a where id in (11,1,111) order by instr('11,1,111',id))  

这样子会有错误,需要通过以下方法进行解决

有两种方式:

1. select id from a where id in (11,1,111) order by instr(',11,1,111,',concat(',',id,',')) 注意要构造多出的, 号

2.(推荐)SELECT * FROM `MyTable`WHERE `id` IN (11,1,111) ORDER BY FIELD(`id`, 11,1,111)//貌似我测试这条语句的时候没有正确出结果

 

有文章指出:

FIELD(str,str1,str2,str3,...)
Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

排序过程:把选出的记录的 id 在 FIELD 列表中进行查找,并返回位置,以位置作为排序依据。

这样的用法,会导致 Using filesort,是效率很低的排序方式。除非数据变化频率很低,或者有长时间的缓存,否则不建议用这样的方式排序。

 

作者建议在程序代码中自行排序,不过我实测过程当中没有发现性能瓶颈。

转自:http://blog.csdn.net/heardy/article/details/8201215

posted on 2015-08-26 10:39  newqzp  阅读(284)  评论(0编辑  收藏  举报

导航