首页 > MySQL
sql 根据in条件排序查询结果
发布时间:2017-08-14 16:43:21
访问量:5

    由于各种的业务需求,sql 查询需要完成各种逻辑,而且很多是临时性的功能需求,所以开发功能的必要性就降低啦,因为时间紧迫等业务条件限制;这样的需求,也接触到了各种罕见的sql语法运用,这次说的就是用sql 根据in查询条件进行排序的结果:

select user_id,mobile from user where user_id in ('714522698ixx','452403fDxx','45241AX0xx',...) order by field(user_id,'714522698ixx','452403fDxx','45241AX0xx',...)

    上面查询的结果就会按照in 条件的顺序排序。

根据实测结果,创建合适的索引,一下两条sql:

explain select user_id,mobile from user where user_id in 
('714522698ixx','452403fDxx','45241AX0xx',...) 
order by field
(user_id,'714522698ixx','452403fDxx','45241AX0xx',...)
explain select user_id,mobile from user where user_id in 
('714522698ixx','452403fDxx','45241AX0xx',...)
explain select user_id,mobile from user where user_id in
 ('714522698ixx','452403fDxx','45241AX0xx',...) 
 order by user_id

使用sql中extra 分别显示:

    Using index condition; Using filesort

    Using where; Using index

    Using where; Using index

所以,第一个sql 不适用于程序中应用,考虑到效率,应该是查询到结果后在程序中foreach 重组结果。

相关文章 更多文章
Navicat 操作数据库传输
Windows7 x86系统下安装MySQL5.5
详解MySQL的操作日志
MySQL常用存储引擎MyIsam和InnoDB的比较
书写Sql文件时常用的注释
发表评论 0
网友评论
© 2010-2015 PekingPiao.com
版权所有 DBR
Mem
Top