本文来源于《一分钟了解索引技巧》的作业题。假设订单业务表结构为:order(oid,date,uid,status,money,time,…)其中:oid,订单ID,主键date,订单日期,有公共索引,管理后台经常查询uid根据日期,用户ID,有一个共同的索引,用户查询自己的订单状态,订单状态,有一个共同的索引,管理后台经常查询钱/时间,订单金额/时间,查询的字段,没有索引...假设订单有3种状态:0已下单,1已付款,2已完成业务需求,查询未完成的订单,哪个SQL更快?select*fromorderwherestatus!=2select*fromorderwherestatus=0orstatus=1select*fromorderwherestatusIN(0,1)select*fromorderwherestatus=0unionallselect*fromorderwherestatus=1结论:方案1最慢,方案2、3、4都可以访问索引但是...1:unionall必须能访问索引select*fromorderwherestatus=0unionallselect*fromorderwherestatus=1解释:直接告诉MySQL怎么做,MySQL消耗CPU最少程序员不常在这写SQL(unionall)方式二:简单incan***indexselect*fromorderwherestatusin(0,1)解释:让MySQL想想,查询优化对cpu的消耗比unionall多,但是可以忽略不计。程序员最常这样写SQL(in)。本例中,推荐写三个:对于or,新版MySQL可以***indexselect*fromorderwherestatus=0orstatus=1说明:让思考MySQL,查询优化比in消耗更多的cpu,不要动手超过MySQL的负担。不建议程序员经常使用or,不是所有or都被索引。对于老版本的MySQL,建议查询分析下四个。,负查询一定不要***indexselect*fromorderwherestatus!=2说明:全表扫描,效率最好,所以最慢的方案是禁止使用否定查询。5.其他方案select*fromorderwherestatus<2在这个具体的例子中,确实很快,但是:这个例子只引用了3个状态,而实际业务不止这3个状态,而状态的“值”正好满足部分顺序关系。在检查其他状态的情况下,SQL不应依赖于枚举的值。该方案不是通用的。该SQL的可读性、理解性和可维护性都很差。强烈不推荐。六。Jobslikethis查询是否能够安装索引?select*fromorderwhereuidin(selectuidfromorderwherestatus=0)select*fromorderwherestatusin(0,1)orderbydatedescselect*fromorderwherestatus=0ordate<=CURDATE()注:此为示例,不对比业务对应的真实SQL的合理性【本文为专栏作者《58神剑》原稿,转载请联系原作者】点此查看该作者更多好文
