How can I simplify multiple 'not in' queries? Is it efficient to use multiple subqueries: Not in (...) and Not in (..) and Not in (..)
I am using count (sorry forgot about that)
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)
Yes, you can! The longer answer is yes, there are a few ways to combine two tables without a common column, including CROSS JOIN (Cartesian product) and UNION. The latter is technically not a join but can be handy for merging tables in SQL.
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)
Why NOT EXISTS?
NOT IN: Any NULL VisitorID values in UserLog or Supplies means no match
(LEFT JOIN): multiple output rows if many UserLog or Supplies per VisitorID. Needs DISTINCT which changes the plan
Generally, NOT EXISTS is the only correct option
You could use a UNION for the id group
Select User
from Company
where VisitorID not in (
select VisitorID from UserLog where ActionID = 2
UNION
select VisitorID from Supplies where productID = 4
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With