重点关注:
1) 没有查询条件,或者查询条件没有建立索引
例如:
select *from tab; 全表扫描。
select* from tab where 1=1;
在业务数据库中,特别是数据量比较大的表。
是没有全表扫描这种需求。
1、对用户查看是非常痛苦的。
2、对服务器来讲毁灭性的。
例如:
select *from tab;
SQL改写成以下语句:
selec* from tab order by price limit 10 需要在price列上建立索引
select * from tab where name='zhangsan' name列没有索引
改:1、换成有索引的列作为查询条件2、将name列建立索引
2) 查询结果集是原表中的大部分数据,应该是25%以上。
查询的结果集,超过了总数行数25%,优化器觉得就没有必要走索引了。
假如:
tab表 id,name id:1-100w ,id列有索引
select * from tab where id>500000;
如果业务允许,可以使用limit控制。
怎么改写 ?
结合业务判断,有没有更好的方式。如果没有更好的改写方案
尽量不要在mysql存放这个数据了。放到redis里面。
3) 索引本身失效,统计数据不真实
索引有自我维护的能力。
对于表内容变化比较频繁的情况下,有可能会出现索引失效。
4) 查询条件使用函数在索引列上,或者对索引列进行运算,运算包括(+,-,*,/,! 等)
例子:
错误的例子:select * from test where id-1=9;
正确的例子:select* from test where id=10;
算术运算
函数运算
desc select * from blog_userinfo where DATE_FORMAT(last_login,'%Y-%m-%d') >= '2019-01-01';
子查询
5)隐式转换导致索引失效.这一点应当引起重视.也是开发中经常会犯的错误.
select * from t1 where telnum=110;
这样会导致索引失效. 错误的例子:------------------------mysql>alter table tab add index inx_tel(telnum);
Query OK,0 rows affected (0.03sec)
Records:0 Duplicates: 0 Warnings: 0mysql>mysql>desc tab;+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | v