Mysql "in" 排序问题
2015-05-13 17:12
561 查看
select * from table where id IN (3,6,9,1,2,5,8,7);
这样的情况取出来后,其实,id还是按1,2,3,4,5,6,7,8,9,排序的,但如果我们真要按IN里面的顺序排序怎么办?SQL能不能完成?是否需要取回来后再foreach一下?
其实可以这样
select * from table where id IN (3,6,9,1,2,5,8,7) order by field(id,3,6,9,1,2,5,8,7);
出来的顺序就是指定的顺序了
关于这种排序的效率,
有文章指出:
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,是效率很低的排序方式。除非数据变化频率很低,或者有长时间的缓存,否则不建议用这样的方式排序。
作者建议在程序代码中自行排序。
但是也有人说这种排序不会出现什么性能瓶颈
具体还是自己测试一下吧。
$result = $model->query("select ".$field." from `mi_city` where id in (".$where.") order by find_in_set('id','".$where."')"); $result = $model->query("select ".$field." from `mi_city` where id in (".$where.")order by find_in_set(id,'".$where."')");
注意上面的两种Sql格式!find_in_set中第一个字段不应该加引号!否则会无效!
相关文章推荐
- Mysql In 排序问题
- mysql in 自定义排序的问题
- mysql in 排序问题:可以按in里面的顺序来排序
- MySQL使用 IN 查询取出数据排序问题(与in排序相同、不排序)
- [ 备忘 ] php 正则表达式与 mysql IN 查询的排序问题
- mysql in 排序问题:可以按in里面的顺序来排序
- 解决 mysql in 查询排序问题
- MYSQL -- 通过in查询怎样排序问题
- mysql问题: "javax.servlet.ServletException: org.gjt.mm.mysql.Driver"
- 快速排序在Top k问题中的运用(quickSort and quickSelect in Top k)
- mysql查询ID排序问题,
- Tensorflow Saver & restore 以及报错问题 NotFoundError: "x_x" not found in checkpoint
- 解决mysql"Access denied for user'root'@'IP地址'"问题
- Exception in thread "http-bio-8080-exec-7"内存溢出问题
- linux上,mysql使用聚合函数group by 时报错:SELECT list is not in GROUP BY clause and contains nonaggre的问题
- nginx -t "nginx: [warn] only the last index in "index" directive should be absolute in 6 "的问题解决
- mysql查询in排序(备忘)
- mysql union order by 分别排序问题
- mysql查询优化--临时表和文件排序(Using temporary; Using filesort问题解决)
- token 6.x-1.17 "preg_match_all() expects parameter 2 to be string, array given in token_scan()" 问题解决