mysql联合索引

    技术2023-07-12  65

    联合索引又叫复合索引。两个或更多个列上的索引被称作复合索引。

    复合索引介绍

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

    索引创建原则

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

    示例

    (1) select * from myTest where a=3 and b=5 and c=4; ---- abc顺序 abc三个索引都在where条件里面用到了,而且都发挥了作用

    (2) select * from myTest where c=4 and b=6 and a=3; where里面的条件顺序在查询之前会被mysql自动优化,效果跟上一句一样

    (3) select * from myTest where a=3 and c=7; a用到索引,b没有用,所以c是没有用到索引效果的

    (4) select * from myTest where a=3 and b>7 and c=3; ---- b范围值,断点,阻塞了c的索引 a用到了,b也用到了,c没有用到,这个地方b是范围值,也算断点,只不过自身用到了索引

    (5) select * from myTest where b=3 and c=4; — 联合索引必须按照顺序使用,并且需要全部使用 因为a索引没有使用,所以这里 bc都没有用上索引效果

    (6) select * from myTest where a>4 and b=7 and c=9; a用到了 b没有使用,c没有使用

    (7) select * from myTest where a=3 order by b; a用到了索引,b在结果排序中也用到了索引的效果,a下面任意一段的b是排好序的

    (8) select * from myTest where a=3 order by c; a用到了索引,但是这个地方c没有发挥排序效果,因为中间断点了,使用 explain 可以看到 filesort

    (9) select * from mytable where b=3 order by a; b没有用到索引,排序中a也没有发挥索引效果

    比对

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

    优: select * from test where order by a 差: select * from test where order by b 差: select * from test where order by c

    优: 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 c

    优: 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 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

    优: 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

    Processed: 0.015, SQL: 9