关于索引的使用技巧

xiaoxiao2021-02-28  59

(1)负向条件查询不能使用索引

select * from order where status!=0 and stauts!=1 not in/not exists都不是好习惯 可以优化为in查询: select * from order where status in(2,3)

(2)前导模糊查询不能使用索引

select * from order where desc like ‘%XX’ 而非前导模糊查询则可以: select * from order where desc like ‘XX%’

(3)数据区分度不大的字段不宜使用索引

select * from user where sex=1 原因:性别只有男,女,每次过滤掉的数据很少,不宜使用索引。

经验上,能过滤80%数据时就可以使用索引。对于订单状态,如果状态值很少,不宜使用索引,如果状态值很多,能够过滤大量数据,则应该建立索引。

(4)在属性上进行计算不能命中索引

select * from order where YEAR(date) < = ‘2017’ 即使date上建立了索引,也会全表扫描,可优化为值计算: select * from order where date < = CURDATE() 或者: select * from order where date < = ‘2017-01-01’

(5)复合索引最左前缀,并不是值SQL语句的where顺序要和复合索引一致

用户中心建立了(login_name, passwd)的复合索引 select * from user where login_name=? and passwd=? select * from user where passwd=? and login_name=? 都能够命中索引

select * from user where login_name=? 也能命中索引,满足复合索引最左前缀

select * from user where passwd=? 不能命中索引,不满足复合索引最左前缀

(6)如果明确知道只有一条结果返回,limit 1能够提高效率

select * from user where login_name=? 可以优化为: select * from user where login_name=? limit 1 原因: 你知道只有一条结果,但数据库并不知道,明确告诉它,让它主动停止游标移动

转载请注明原文地址: https://www.6miu.com/read-56783.html

最新回复(0)