MYSQL索引优化: IN 和 OR 替换为 union all

来源:互联网 发布:淘宝卖什么吃的赚钱 编辑:程序博客网 时间:2024/05/17 04:07
MySQL会对sql语句做优化, IN 后面的条件不超过一定数量仍然会使用索引。mysql 会根据索引长度和in后面条件数量判断是否使用索引。

另外,如果是 IN 后面是子查询,则不会使用索引

一个文章库,里面有两个表:category和article。

category里面有10条分类数据。

article里面有 20万条。article里面有一个"article_category"字段是与category里的"category_id"字段相对应的。

 article表里面已经把 article_category字义为了索引。

数据库大小为1.3G。


问题描述:
执行一个很普通的查询: select * from`article` where article_category=11 order by article_id desc limit 5 。执行时间大约要5秒左右

解决方案
建一个索引:create index idx_u on article (article_category,article_id);
select * from`article` Where article_category=11 order by article_id desc limit 5 减少到0.0027秒

继续问题:

select *  from `article`  where article_category IN (2,3) order by article_iddesc limit  5 执行时间要11.2850秒。
或者使用 
or:

select * from article where article_category=2  or article_category=3 order by article_id desc limit 5
执行时间:11.0777


解决方案

避免使用in 或者 or ( or 会导致扫表),使用union all

( select * from article where article_category=2 order by article_id desc limit 5 )
UNION ALL  (select * from article where article_category=3 order by article_id desc limit 5 )
order by article_id desc limit 5

执行时间:0.0261


原创粉丝点击