您好,欢迎访问一九零五行业门户网

MySQL 查询优化之 or

当使用or的时候是不会用到索引的
mysql> explain select * from aladdin_resource wherestate = 1 or state = 2;+----+-------------+------------------+------+---------------+------+---------+------+-------+-------------+| id | select_type | table| type | possible_keys | key| key_len | ref| rows| extra |+----+-------------+------------------+------+---------------+------+---------+------+-------+-------------+|1 | simple| aladdin_resource | all| state | null | null| null | 59074 | using where |+----+-------------+------------------+------+---------------+------+---------+------+-------+-------------+1 row in set (0.00 sec)
解决办法就是用union替换or
explain select * from aladdin_resource where state=1 union select * from aladdin_resource where state=2;+----+--------------+------------------+------+---------------+-------+---------+-------+-------+-------------+| id | select_type| table| type | possible_keys | key | key_len | ref | rows| extra |+----+--------------+------------------+------+---------------+-------+---------+-------+-------+-------------+|1 | primary| aladdin_resource | ref| state | state | 2 | const | 383 | using where ||2 | union| aladdin_resource | ref| state | state | 2 | const | 21370 | using where || null | union result | | all| null| null| null| null|null | |+----+--------------+------------------+------+---------------+-------+---------+-------+-------+-------------+3 rows in set (0.05 sec)
高下立判
其它类似信息

推荐信息