时间:2021-07-01 10:21:17 帮助过:5人阅读
但请注意的是:优化只针对SELECT有效,对UPDATE/DELETE子查询无效,固生产环境应避免使用子查询
2.避免函数索引
例:
SELECT * FROM t WHERE YEAR(d) >= 2016;
由于MySQL不像Oracle那样支持函数索引,即使d字段有索引,也会直接全表扫描。
应改为----->
SELECT * FROM t WHERE d >= ‘2016-01-01‘;
3.用IN来替换OR
低效查询
SELECT * FROM t WHERE LOC_ID = 10 OR LOC_ID = 20 OR LOC_ID = 30;
----->
高效查询
SELECT * FROM t WHERE LOC_IN IN (10,20,30);
4.LIKE双百分号无法使用到索引
SELECT * FROM t WHERE name LIKE ‘%de%‘;
----->
SELECT * FROM t WHERE name LIKE ‘de%‘;
5、读取适当的记录LIMIT M,N
SELECT * FROM t WHERE 1;
----->
SELECT * FROM t WHERE 1 LIMIT 10;
6、避免数据类型不一致
SELECT * FROM t WHERE id = ‘19‘;
----->
SELECT * FROM t WHERE id = 19;
7、分组统计可以禁止排序
SELECT goods_id,count(*) FROM t GROUP BY goods_id;
默认情况下,MySQL对所有GROUP BY col1,col2...的字段进行排序。如果查询包括GROUP BY,想要避免排序结果的消耗,则可以指定ORDER BY NULL禁止排序。
----->
SELECT goods_id,count(*) FROM t GROUP BY goods_id ORDER BY NULL;
9、禁止不必要的ORDER BY排序
SELECT count(1) FROM user u LEFT JOIN user_info i ON u.id = i.user_id WHERE 1 = 1 ORDER BY u.create_time DESC;
----->
SELECT count(1) FROM user u LEFT JOIN user_info i ON u.id = i.user_id;
SQL语句常见优化十大案例
标签:逻辑 rac key esc -- order by class 数据库 生产