mysql 单列索引与联合索引的使用

mac2026-08-18  2

一、单列索引

col1,col2,col3 分别加索引i1,i2,i3

select * from t where col1 = 'v'  用了索引 i1

select * from t where col1 = 'v' and col2 = 'v' and col3 = 'v' 还是只用了索引 i1

select * from t where col2 = 'v' and col1 = 'v' and col3 = 'v' 还是只用了索引 i1

select * from t where col2 = 'v' and col3 = 'v' 用了i2

用or的时候

select * from t where col1 = 'v' or col2 = 'v'  未用任何索引

其他特殊情况

select * from student where  1=1 and sname = '小明2'  会使用索引

select * from student where  sname = ' '     会使用索引

select * from student where  sname = null  不会用索引  (所以避免给字段设置null)

 

二、联合索引

col1,col2,col3 创建联合索引 i123

均使用了索引i123 :

    where col1

    where col1 and col2

    where col1 and col2 and col3

    where col1 and col3

未能使用索引:

    where col2

    where col2 and col3

三、单列索引和联合索引作用在一个列中

与上述规则一致。

当两个索引都可以用到时,数据库引擎自动优化,自动选择最快的那个索引。

 

最新回复(0)