Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Sub-Query with "not in" operator to join

Is it possible to convert a sub-query with NOT IN operator to join? I need this query using joins

SELECT *
FROM Contacts
WHERE ContactIntID NOT IN(
    SELECT LinkToIntID
    FROM Requirements
    WHERE Requirements.uuJobStatus = 'Open')
like image 916
Ram Grandhi Avatar asked Sep 20 '25 01:09

Ram Grandhi


2 Answers

Yes.

SELECT c.*
FROM Contacts c
LEFT JOIN 
  (SELECT LinkToIntID FROM Requirements WHERE uuJobStatus='Open') r 
  ON (c.ContactIntID=r.LinkToIntID)
WHERE r.LinkToIntID IS NULL

and simplified:

SELECT c.*
FROM Contacts c
LEFT JOIN 
  Requirements r 
  ON  r.uuJobStatus = 'Open'
  AND c.ContactIntID = r.LinkToIntID
WHERE r.LinkToIntID IS NULL
like image 161
geomagas Avatar answered Sep 22 '25 19:09

geomagas


Using non exists will generally perform better than using LEFT JOIN. With the above answers, the contacts will join all records regardless whether they match or not, and then filter them out later using the IS NULL clause.

SELECT *
FROM Contacts c
WHERE NOT EXISTS
(
    SELECT 1
    FROM Requirements r
    WHERE Requirements.uuJobStatus = 'Open'
    AND ContractIntID = r.LinkToIntID
)

Edit: Realised you wanted a non sub query, but nevertheless worth noting my reply :)

like image 34
user172839 Avatar answered Sep 22 '25 20:09

user172839