sqlserver not in 语句使程充崩溃

两张表 组织架构表(organise) 和 工资发放历史记录表 (wagepermonthhis)

两张表通过 organise.item_id 和 wagepermonthhis.orgids 进行关联

organise表(以下简称o表)中大约有6000条记录11个字段 ,wagepermonthhis(以下简称w表)计有 125万条记录 和 25个字段

原程序中一段如下的语句

是查询所有不在w表的组织架构层级为2的记录


复制代码 代码如下:

select orgid as 公司编码,orgname as 公司名称

from organise

where orglev=2

and item_id not in

(select orgids from wagespermonthhis

where wagesyear=’2010′ and wagesmonth=

’01’ group by orgids,orgnames)

order by orgid

语句执行要33秒之久,服务器的配置是比较高的:16核心4cpu,24g内存,且内存和cpu在执行时都没有出现瓶颈,开始以为是 (select orgids from wagespermonthhis

where wagesyear=’2010′ and wagesmonth=

’01’ group by orgids,orgnames) 这条语句执行缓慢所致,单独执行这条却发现执行速度很快,大约不到2秒就出来了,于是症结出来了,是not in 这个全扫描关键词带来的性能下降.最直接的是导致页面失去响应,一个关键功能使用不了.

试了not exist语句,发现效果是一样的,并不象网上所说可以提高很多性能.

于是重新优化语句如下


复制代码 代码如下:

select a.orgid as 公司编码,a.orgname as 公司名称,a.item_id

from organise a

left outer join (select distinct b.orgids from wagespermonthhis b

where wagesyear=’2010′ and wagesmonth=’01’) as b

on a.item_id = b.orgids

where a.orglev = 2

and b.orgids is null

order by 公司编码

改用左外连接(其实左连接也可以)后,整个语句执行速度为400ms, 33秒与400ms 我想是很多人没想到的.

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐