不适合建立索引的情况

2019-11-07  本文已影响0人  木木呦

不适合建立索引的情况

1. 在查询中很少使用的列。

2. 很少数据值的列,例如:性别

3. 对于text,image,bit这样大数据列的字段,因为这些字段数据量要么非常大要么很少。

4. 当修改性能大于查询性能时,不应该去建立索引。


MySQL优化

1. 避免全表扫描,首先应在where及order by后面设计的列上建立索引。

2. 因尽量避免在where子句中进行null值判断,否则将导致引擎放弃索引,进行全盘扫描。

    例如:select * from table where name is null   可以将null设置成默认值0

3. 因尽量避免在where子句中使用!= ,<>。

4. 因尽量避免在where子句中使用or,因为or是左右两种要同时进行查询。

    例如:select id from table where num = 1 or num = 3

    改为:select id from table where num = 1

                union all

                select id from table where num =3

5. in 和 not in 也要慎用。

select id from table where num in (1,2,3)

对于连续的数值可以使用between ...and

6. 模糊查询,like前有%的不会走索引。

7. where字句进行表达式运算,或者使用函数都不会走索引。

运算:select id from table where num/2 = 100不会走索引

改为:select id from table where num = 100 * 2

函数:select id from table where substring(name, 1, 3) = 'abc'不会走索引

8. 在使用索引字段作为条件时,如果是复合索引,那么必须使用到该索引中的第一个字段作为条件时,才能保证系统使用索引。

补:例如三个字段num,name, age建立联合索引(num_name_age),实际可用索引为三种,num,num_name,num_age

9. 使用exists代替(exists执行完的返回true或false,true才执行外侧语句,否则不执行。)

select id from table where num in (select num from table2 )

改为:

select id from table where exists(select 1 from table2 where num = table.num)

上一篇 下一篇

猜你喜欢

热点阅读