• mysql in 排序 也可以按in里面的顺序来排序


    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。
    建议在程序代码中自行排序。

  • 相关阅读:
    HTML初步学习7
    HTML初步学习6
    HTML初步学习5
    HTML初步学习4
    poj3449Geometric Shapes
    poj2074Line of Sight(直线相交)
    2014 Multi-University Training Contest 4
    poj3347Kadj Squares
    poj1556The Doors
    poj3608Bridge Across Islands(凸包间最小距离)
  • 原文地址:https://www.cnblogs.com/wayne173/p/6714259.html
Copyright © 2020-2023  润新知