mysql笔记(4)-复合索引的性能问题

11月 2, 2008 – 8:50 上午

昨天有个朋友谈起复合索引,之前对复合索引只是大概了解没有专门的总结也不敢多言复合索引使用方法的优劣.查阅相关资料后把例子贴出与大家分享,希望可以抛砖引玉.

对于复合索引:Mysql从左到右的使用索引中的字段,一个查询可以只使用索引中的一部份,但只能是最左侧部分。例如索引是key index (a,b,c). 可以支持a | a,b| a,b,c 3种组合进行查找,但不支持 b,c进行查找 .当最左侧字段是常量引用时,索引就十分有效。下面用几个例子对比查询条件的不同对性能影响.

  1. create table test(
  2.   a int,
  3.   b int,
  4.   c int,
  5.   KEY a(a,b,c)
  6. );
  7.  
  8. 优: select * from test where a=10 and b>50
  9. 差: select * from test where a<10 and b>50
  10.  
  11. 优: select * from test where  order by a
  12. 差: select * from test where  order by b
  13. 差: select * from test where  order by c
  14.  
  15. 优: select * from test where  a=10 order by a
  16. 优: select * from test where  a=10 order by b
  17. 差: select * from test where  a=10 order by c
  18.  
  19. 优: select * from test where  a>10 order by a
  20. 差: select * from test where  a>10 order by b
  21. 差: select * from test where  a>10 order by c
  22.  
  23. 优: select * from test where  a=10 and b=10 order by a
  24. 优: select * from test where  a=10 and b=10 order by b
  25. 优: select * from test where  a=10 and b=10 order by c
  26.  
  27. 优: select * from test where  a=10 and b=10 order by a
  28. 优: select * from test where  a=10 and b>10 order by b
  29. 差: select * from test where  a=10 and b>10 order by c

索引原则

1.索引越少越好
原因:主要在修改数据时,第个索引都要进行更新,降低写速度。
2.最窄的字段放在键的左边
3.避免file sort排序,临时表和表扫描.


  1. 11 Responses to “mysql笔记(4)-复合索引的性能问题”

  2. 坐臭皮匠沙发,走健康之路

    [回复此评论]

    果沟 reply on 11月 3, 2008:

    晕,沙发被你搞破了快。把你加到朋友链里边,看我抢你沙发

    [回复此评论]

    老时 reply on 11月 6, 2008:

    嘿嘿

    [回复此评论]

    By on Nov 2, 2008

  3. 呵呵,老时喜欢坐地板。。

    [回复此评论]

    By on Nov 3, 2008

  4. 学习mysql中……
    哈哈

    [回复此评论]

    By zylew on Nov 4, 2008

  5. 很专业啊,以后电脑问题多向你请教。

    [回复此评论]

    果沟 reply on 11月 7, 2008:

    乐意帮忙。

    [回复此评论]

    By kongcuo on Nov 7, 2008

  6. 不好意思,本来我也应该在首页链接你的博客。但因为贵站的主题和我的主题实在有所不同,因此放在了link页面,望见谅。

    [回复此评论]

    By kongcuo on Nov 7, 2008

  7. 链接已经给你加上了啊

    [回复此评论]

    By zonghua on Nov 10, 2008

  8. 博主是搞PHP开发的?

    [回复此评论]

    果沟 reply on 11月 11, 2008:

    当前做web开发

    [回复此评论]

    By zonghua on Nov 11, 2008

Post a Comment