SQL优化简单总结
-
查询优化
-
避免全表扫描,优先考虑在where和order by涉及的列上建立索引
-
is null值判断会导致引擎放弃使用索引,变成全表扫描,如:
select id from t where num is null -- 导致全表扫描
- !=或<>操作符也会导致引擎放弃使用索引,进行全表扫描,如:
select id from t where num <> 0 -- 导致全表扫描
- or在条件不都有索引的情况下,导致放弃使用索引进行全表扫描,如:
select id from t where num=10 or Name = 'admin'
可以改成这样查询
select id from t where num = 10 union all select id from t where Name = 'admin'
- in和not in会导致全表扫描,用exists代替in,如:
select id from t where num in(1,2,3)
用exists代替in,如:
select num from a where num in(select num from b)
替换成
select num from a where exists(select 1 from b where num=a.num)
- like查询前置%会导致全表查询,如
select id from t where name like ‘%abc%’
- where中的字段运算操作会导致全表扫描,如:
select id from t where num/2 = 100
应改为
select id from t where num = 100*2
- where中的字段进行函数操作会导致不走索引进行全表扫描,如:
select id from t where substring(name,1,3) = ’abc’
应改为:
select id from t where name like 'abc%'
总结7,8,为where语句中的字段**=**左边进行函数,算数或其他表达式,引擎将不走索引,进行全表查询
-
-
大数据量操作优化
实际案例分析:拆分大的 DELETE 或INSERT 语句,批量提交SQL语句
如果你有一个大的处理,你一定把其拆分,使用 LIMIT oracle(rownum),sqlserver(top)条件是一个好的方法。下面是一个mysql示例:
while(1){
//每次只做1000条
mysql_query(“delete from logs where log_date <= ’2012-11-01’ limit 1000”);
if(mysql_affected_rows() == 0){
//删除完成,退出!
break;
}
//每次暂停一段时间,释放表让其他进程/线程访问。
usleep(50000)
}