如何简化多个“不在”查询?使用多个子查询是否有效:不在(...),不在(..)和不在(..)

我正在使用count(对不起,忘了这一点)

 Select count (VisitorID)

 from Company

 where VisitorID not in (select VisitorID from UserLog where ActionID = 2 )

 and VisitorID not in (select VisitorID from Supplies where productID = 4)

最佳答案

Select count (VisitorID)

from Company C
where
NOT EXISTS (select * from UserLog U where ActionID = 2 AND C.VisitorID  = U.VisitorID)
AND
NOT EXISTS (select * from Supplies S where productID = 4 AND S.VisitorID  = U.VisitorID)

为什么不存在?
  • NOT IN:UserLog或Supplies中的任何NULL VisitorID值都表示不匹配
  • (LEFT JOIN):如果每个VisitorID包含许多UserLog或Supplies,则输出多个行。需要DISTINCT来更改计划

  • 通常,不存在是唯一正确的选择

    关于sql - 对多个表使用NOT IN,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3805153/

    10-11 04:42