Mysql常见sql语句优化
SQL语句优化
-
不要把SELECT子句写成 SELECT *
SELECT * FROM t_emp;
-
谨慎使用模糊查询
SELECT ename FROM t_emp WHERE ename LIKE '%S%'; #不使用索引 SELECT ename FROM t_emp WHERE ename LIKE 'S%';
-
对ORDER BY排序的字段设置索引
SELECT ename FROM t_emp order by deptno
-
少用IS NULL
SELECT ename FROM t_emp WHERE comm IS NULL; SELECT ename FROM t_emp WHERE comm =-1;
-
尽量少用 != 运算符
SELECT ename FROM t_emp WHERE deptno!=20; SELECT ename FROM t_emp WHERE deptno<20 AND deptno>20;
-
尽量少用 OR 运算符
SELECT ename FROM t_emp WHERE deptno=20 OR deptno=30; #不使用索引 SELECT ename FROM t_emp WHERE deptno=20 UNION ALL SELECT ename FROM t_emp WHERE deptno=30;
-
尽量少用 IN 和 NOT IN 运算符
SELECT ename FROM t_emp WHERE deptno IN (20,30); #不使用索引 SELECT ename FROM t_emp WHERE deptno=20 UNION ALL SELECT ename FROM t_emp WHERE deptno=30;
java开发手册
-
避免条件语句中的数据类型转换
SELECT ename FROM t_emp WHERE deptno='20';
-
在表达式左侧使用运算符和函数都会让索引失效
SELECT ename FROM t_emp WHERE salary*12>=100000; #不使用索引 SELECT ename FROM t_emp WHERE salary>=100000/12; SELECT ename FROM t_emp WHERE year(hiredate)>=2000; #不使用索引 SELECT ename FROM t_emp WHERE hiredate>='2000-01-01 00:00:00';
License:
CC BY 4.0