Sql server not in优化

使用EXISTS(或NOT EXISTS)通常将提高查询的效率,由于NOT IN子句将对子查询中的表执行了一个全表遍历。

oracle在执行IN子查询过程中,先执行子查询结果放入临时表再进行主查询;
 
而exists先运行主查询,再执行子查询查到第一个匹配项
如:查询 A表中没有和B表或C表相连的数据 
 
select A.id,A.reads,A.addtime 
from A 
where A.person_id not in (select user_id from B ) 
or A.worksite_id not in (select id from C) 
order by A.addtime desc
程序执行时间:40109.38毫秒 
 
select A.id,A.reads,A.addtime
from A 
where not exists (select id FROM B where B.user_id=A.person_id) 
or not exists (select id FROM C where C.id=A.worksite_id) 
order by Sendorder.addtime desc
程序执行时间:8531.25毫秒 

 

ms ssql 实例:

复制代码
select 
subscriber_id
from 
NewsLetterSystem_CampaignCategorySubscriber ccs WITH ( NOLOCK )
where NOT EXISTS(
SELECT  distinct subscriber_id
FROM    NewsLetterSystem_OpenTracking ot WITH ( NOLOCK ) 
WHERE  ot.subscriber_id=ccs.subscriber_id and ot.campaign_id = 52801)
and ccs.campaign_id = 52801 and ccs.status_id = 1
复制代码

 

posted @   大空白纸  阅读(1443)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示