函数操作
对条件字段做函数操作,可能破坏了索引值的有序性,走不了索引。
select * from t1 where date(c) ='2019-05-21';
优化:改成范围查询
select * from t1 where c>='2019-05-21 00:00:00' and c<='2019-05-21 23:59:59';
隐式转换
操作符与不同类型的操作对象一起使用时,就会发生类型转换以使操作兼容。
select user_name,tele_phone from user_info where tele_phone =11111111111; /* tele_phone varchar */
实际会做函数操作:
select user_name,tele_phone from user_info where cast(tele_phone as singed int) =11111111111;
优化:类型统一
select user_name,tele_phone from user_info where tele_phone ='11111111111';//字符串转数字
模糊查询
通配符在前面
select * from t1 where a like '%1111%';
优化:模糊查询必须包含条件字段前面的值
select * from t1 where a like '1111%';
范围查询
范围查询数据量太多,需要回表,因此不走索引。
select * from t1 where b>=1 and b <=2000;
优化:降低单次查询范围,分多次查询。(实际可能速度没得快太多,建议走索引)
select * from t1 where b>=1 and b <=1000;
show profiles;
+----------+------------+------------------------------------------+
| Query_ID | Duration | Query |
+----------+------------+------------------------------------------+
| 1 | 0.00534775 | select * from t1 where b>=1 and b <=1000 |
| 2 | 0.00605625 | select * from t1 where b>=1 and b <=2000 |
+----------+------------+------------------------------------------+
2 rows in set, 1 warning (0.00 sec)
计算操作
即使是简单的计算
explain select * from t1 where b-1 =1000;
优化:将计算操作放在等号后面
explain select * from t1 where b =1000 + 1;