10条SQL优化语句,让你的数据库跑得更快!

时间:2022-02-21 23:59:06
1不使用子查询

例:SELECT * FROM t1 WHERE id (SELECT id FROM t2 WHERE name='hechunyang');


子查询在MySQL5.5版本里,内部执行计划器是这样执行的:先查外表再匹配内表,而不是先查内表t2,当外表的数据很大时,查询速度会非常慢。

在MariaDB10/MySQL5.6版本里,采用join关联方式对其进行了优化,这条SQL会自动转换为
SELECT t1.* FROM t1 JOIN t2 ON t1.id = t2.id;

但请注意的是:优化只针对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);

4LIKE双百分号无法使用到索引

SELECT * FROM t WHERE name LIKE '%de%';
----->
SELECT * FROM t WHERE name LIKE 'de%';
目前只有MySQL5.7支持全文索引(支持中文)

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;

8避免随机取记录

SELECT * FROM t1 WHERE 1=1 ORDER BY RAND() LIMIT 4;
MySQL不支持函数索引,会导致全表扫描
----->
SELECT * FROM t1 WHERE id >= CEIL(RAND()*1000) LIMIT 4;       

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;

10批量INSERT插入

INSERT INTO t (id, name) VALUES(1,'Bea');
INSERT INTO t (id, name) VALUES(2,'Belle');
INSERT INTO t (id, name) VALUES(3,'Bernice');
----->
INSERT INTO t (id, name) VALUES(1,'Bea'), (2,'Belle'),(3,'Bernice');