sql 记录一下,not in 和 exists

--虚拟字段,asortid,且1是它的值,比在表上虚拟个字段,扩展性更好,在做表的差值运算时,not exists 要比 not in 的效率高

--not EXISTS
select aRealID as aID,aNameMain,aAddTime,1 as aSortID from dbo.ArticleShow where aSiteID=2 and aIsCommendSite=1
union all
select a.aID,a.aNameMain,a.aAddTime,0 as aSortID from ArticleCache_2008 as a where aStatus=1 and NOT EXISTS
(select b.aRealID from ArticleShow  as b where a.aID=b.aRealID and b.aSiteID=2) order by aSortID desc,aAddTime desc

--not in
select aRealID as aID,aNameMain,1 as aSortID,aAddTime from dbo.ArticleShow where aSiteID=2 and aIsCommendSite=1
union all
select aID,aNameMain,0 as aSortID,aAddTime from ArticleCache_2008 where aStatus=1 and aID not in
 (select aRealID as aID from ArticleShow where aSiteID=2) order by aSortID desc,aAddTime desc

原文地址:https://www.cnblogs.com/suneryong/p/1307880.html