MySQL 查询优化之 or

WBOY
发布: 2016-05-31 08:48:54
原创
1849 人浏览过

当使用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 | <union1,2> | ALL| NULL| NULL| NULL| NULL|NULL | |+----+--------------+------------------+------+---------------+-------+---------+-------+-------+-------------+3 rows in set (0.05 sec)
登录后复制

高下立判

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板