MySQL's or/in/union and index optimization

Suppose the order business table structure is:

order(oid, date, uid, status, money, time, …)

in:

  • oid , order id , primary key

  • date , the date of the order, there is a common index , the management background often queries according to date

  • uid , user ID , there is a common index , users can query their own orders

  • status , the order status, there is a common index , the management background is often queried according to the status

  • money/time , order amount /time , queried field, no index

 

Suppose an order has three states: 0 Ordered, 1 Paid, 2 Completed

Business requirements, query outstanding orders, which SQL is faster?

  • select * from order where status!=2

  • select * from order where status=0 or status=1

  • select * from order where status IN (0,1)

  • select * from order where status=0

    union all

    select * from order where status=1


Conclusion: Scheme 1 is the slowest, schemes 2, 3, and 4 can all hit the index


but... 


One: union all  must be able to hit the index

select * from order where status=0

union all

select * from order where status=1

illustrate:

  • Tell MySQL directly what to do, MySQL consumes the least CPU

  • Programmers don't often write SQL like this (union all)

 

Two: simple in can hit the index

select * from order where status in (0,1)

illustrate:

  • Let MySQL think, query optimization consumes more CPU than union all , but it can be ignored

  • Programmers often write SQL(in) like this. In this example, it is most recommended to write like this

 

Three: For or , the new version of MySQL can hit the index

select * from order where status=0 or status=1

illustrate:

  • MySQL思考,查询优化耗费的cpuin,别把负担交给MySQL

  • 不建议程序员频繁用or,不是所有的or都命中索引

  • 对于老版本的MySQL,建议查询分析下

 

四、对于!=,负向查询肯定不能命中索引

select * from order where status!=2

说明:

  • 全表扫描,效率最低所有方案中最慢

  • 禁止使用负向查询

 

五、其他方案

select * from order where status < 2

这个具体的例子中,确实快,但是:

  • 这个例子只举了3个状态,实际业务不止这3个状态,并且状态的“值”正好满足偏序关系,万一是查其他状态呢,SQL不宜依赖于枚举的值,方案不通用

  • 这个SQL可读性差,可理解性差,可维护性差,强烈不推荐

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324601604&siteId=291194637