mysql 联合索引详解

mysql 联合索引详解mysql

联合索引又叫复合索引。对于复合索引:Mysql从左到右的使用索引中的字段,一个查询能够只使用索引中的一部份,但只能是最左侧部分。例如索引是key index (a,b,c). 能够支持a | a,b| a,b,c 3种组合进行查找,但不支持 b,c进行查找 .当最左侧字段是常量引用时,索引就十分有效。sql

两个或更多个列上的索引被称做复合索引。
利用索引中的附加列,您能够缩小搜索的范围,但使用一个具备两列的索引 不一样于使用两个单独的索引。复合索引的结构与电话簿相似,人名由姓和名构成,电话簿首先按姓氏对进行排序,而后按名字对有相同姓氏的人进行排序。若是您知 道姓,电话簿将很是有用;若是您知道姓和名,电话簿则更为有用,但若是您只知道名不姓,电话簿将没有用处。
因此说建立复合索引时,应该仔细考虑列的顺序。对索引中的全部列执行搜索或仅对前几列执行搜索时,复合索引很是有用;仅对后面的任意列执行搜索时,复合索引则没有用处。
如:创建 姓名、年龄、性别的复合索引。排序

create table test(
a int,
b int,
c int,
KEY a(a,b,c)
);索引

优: select * from test where a=10 and b>50
差: select * from test where a50table

优: select * from test order by a
差: select * from test order by b
差: select * from test order by ctest

优: select * from test where a=10 order by a
优: select * from test where a=10 order by b
差: select * from test where a=10 order by cfile

优: select * from test where a>10 order by a
差: select * from test where a>10 order by b
差: select * from test where a>10 order by cselect

优: select * from test where a=10 and b=10 order by a
优: select * from test where a=10 and b=10 order by b
优: select * from test where a=10 and b=10 order by c搜索

优: select * from test where a=10 and b=10 order by a
优: select * from test where a=10 and b>10 order by b
差: select * from test where a=10 and b>10 order by c引用


索引原则

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