sql优化
未整理
一,减少 select *
语句,尽量使用覆盖索引。
二,where与on的执行顺序。
三,inner join、left join。
1.left join 的on 不能写右表的条件 (如rtable.id='11'、 rtable.id in ('1') )
四,最好不用(!= 、<> 、in、not in、not exists,使用Left join代替
1.举例一:not in ->left join
批量把B表中A表没有的数据放入A表中。
not in写法:
1 Insert 2 into Inven1( 3 cInvSubCode 4 , fBuyExcess 5 , iSurenessType 6 , iDateType 7 ) 8 select 9 cInvSubCode 10 , fBuyExcess 11 , iSurenessType 12 , iDateType 13 from 14 Inven2 15 where 16 cInvSubCode NOT IN (select cInvSubCode From Inven1)
起初我想用【判断插入的数据在表中存不存在】中的方法(先IF NOT EXISTS 判断,然后插入),但是那个是为单条数据设计的;所以需要寻求用left join等方式代替。
left join写法:
1 Insert 2 into Inven1( 3 cInvSubCode 4 , fBuyExcess 5 , iSurenessType 6 , iDateType 7 ) 8 select 9 b.cInvSubCode 10 , b.fBuyExcess 11 , b.iSurenessType 12 , b.iDateType 13 from 14 Inven2 b left join Inven1 a 15 on a.cInvSubCode=b.cInvSubCode 16 where 17 a.iDateType is null
2.举例二:in ->left join
同理,批量把B表中A表有的数据更新到A表中
见:https://www.cnblogs.com/zhangdk/p/notintoleftjoin.html
五,事务优化
1.善用视图与临时表:
如:先查后删的事务可以使用临时表优化,查询的数据保存在临时表里,读取临时表的数据作为删除条件
--保存为临时表 select * into #tmp from table1 --查询临时表 select * from #tmp --删除临时表 drop table #tmp
注意:修改临时表的数据不会影响原表数据,修改视图会影响原表的数据
举例一(特殊例:mssql中带left与where的sql,where的范围为left前的整个表,不受left筛选结果的影响):临时表的作用
环境:2008、2016、2019
2. 可以要用脏读With (NoLock)处理死锁,但是要慎重,会造成数据不全或者多出来一些。
请看解读:https://www.cnblogs.com/luckjason/archive/2012/06/26/2563361.html、
https://www.cnblogs.com/lgxlsm/p/10684080.html
六,分页查询优化
本文来自博客园,作者:꧁执笔小白꧂,转载请注明原文链接:https://www.cnblogs.com/qq2806933146xiaobai/p/15532873.html