sql in按照指定顺序排序 mysql in 排序 也可以按in里面的顺序来排序

https://www.cnblogs.com/xiaoliu66007/p/5817219.html

https://www.cnblogs.com/wayne173/p/6714259.html

Select *

FROM table1

Where ID IN (3,5,1,4,2)

order by field (ID,3,5,1,4,2)

SQL: select * from table where id IN (3,9,6);

这样的情况取出来后,其实,id还是按3,6,9,排序的,但如果我们真要按IN里面的顺序排序怎么办?SQL能不能完成?是否需要取回来后再foreach一下?

其实可以这样

sql: select * from table where id IN (3,9,6) order by field(id,3,9,6);

出来的顺序就是指定的(3,6,9)顺序了

关于这种排序的效率,

有文章指出:

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,是效率很低的排序方式。除非数据变化频率很低,或者有长时间的缓存,否则不建议用这样的方式排序。

使用explain测试会导致using filesort。

建议在程序代码中自行排序。

SQL: select * from table where id IN (3,9,6);

这样的情况取出来后,其实,id还是按3,6,9,排序的,但如果我们真要按IN里面的顺序排序怎么办?SQL能不能完成?是否需要取回来后再foreach一下?

其实可以这样

sql: select * from table where id IN (3,9,6) order by field(id,3,9,6);

出来的顺序就是指定的(3,6,9)顺序了

关于这种排序的效率,

有文章指出:

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,是效率很低的排序方式。除非数据变化频率很低,或者有长时间的缓存,否则不建议用这样的方式排序。

使用explain测试会导致using filesort。

建议在程序代码中自行排序。