创建博客 登录  
 关注
   显示下一条  |  关闭

懒者空间

选择需要无悔的坚持!

 
 
 

日志

 
 

【引用】关于MYSQL索引优化和in or替换为union all  

2011-08-16 11:19:21|  分类: MySQL |  标签: |字号 订阅

一个文章库,里面有两个表: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_id DESC 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

使用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

  评论这张
转发至微博
转发至微博
0   分享到:        
阅读(96)| 评论(0)| 引用 (0) |举报

历史上的今天

相关文章

最近读者

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--相关文章--> <#--历史上的今天--> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2012