1、如何进行SQL优化
01、对sql进行优化应该避免进行全表搜索,应该在where或order by 的字段建立索引。
02、应该避免where 字句中写 != 或 <>,不然搜索引擎会放弃索引进行全表查询。
03、应该不要使用 is null 语句,搜索引擎会放弃索引进行全表查询。
select * from x where a is null ,将a默认值设为0,select * from x where a = 0;
04、尽可能不要使用 or 来进行拼接条件,否则将导致引擎放弃使用索引而进行全表扫描,如:
selec * from a where s=10 or b=10 换成 select * from a where s = 10 union all selecr * from a where b =10;
05、not in 和 in 也要慎用 ,因为这个会导致全表扫描。 连续的值可以用between 1 and 3代替
06、对筛选的字段不要用表达式,因为会进行全表扫描,如。
select id from t where num/2=100改为
select id from t where num=100*2
07、.很多时候用 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)
08、任何地方都不要使用 select * from t ,用具体的字段列表代替“*”,不要返回用不到的任何字段。
参考文档: