Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using NOT IN for multiple tables

Tags:

sql

tsql

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)
like image 248
Stewie Griffin Avatar asked Sep 27 '10 15:09

Stewie Griffin


People also ask

Can we join 2 tables without on condition?

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.


2 Answers

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

like image 141
gbn Avatar answered Oct 16 '22 14:10

gbn


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
)
like image 32
il_guru Avatar answered Oct 16 '22 13:10

il_guru