数据库学习记录(查询优化)
SQL查询优化
-
原则:尽量让SQL命中索引,提升查询性能
-
最左前缀法则:在使用联合索引时,需要从左开始匹配
-
如联合索引为name、age、phone
-
全部命中
where name = 'tom' and age = 18 and phone = '13488888888'
-
命中name和age
where name = 'tom' and age = 18
-
命中name
where name = 'tom' and phone = '13488888888'
-
全部命中(由于查询优化器对该sql进行优化)
where name = 'tom' and phone = '13488888888' and age = 18
-
未命中(or使索引失效)
where name = 'tom' and age = 18 or phone = '13488888888'
索引失效的情况
-
使用 !=
-
使用 or
-
使用null进行判断
-
索引列进行运算
-
使用左匹配,name like '%tom'
-
字符串比较丢失引号,如a = '1' 写成 a = 1
-
分页查询时数据量太大
-
in中的元素数超过1000
Explain:可以用来判断是否命中索引
-
主要关注字段:
-
type:一般需要为range,最好到达ref
-
key:实际命中的索引
-
key_len:命中索引的长度
-
extra:扩展消息,如果为Using_index,就是触发了索引覆盖
-