camilo93.cc
camilo93.cc

Reputation: 147

Left join to same table SQL

I am trying to make a left join to the same table in the same query but the result is not okey, I resolved the problem with a subquery this is the wrong query:

SELECT * FROM TableA ta
  LEFT JOIN TableA Lta ON ta.key = Lta.key
  AND ta.state IN('C')
  AND Lta.state IN ('A','E')
WHERE Lta.key is null

This is the way how I resolved

SELECT * FROM (
  SELECT * FROM TableA ta
  WHERE ta.state IN('C')
) AS T LEFT JOIN TableA Lta ON T.key =  Lta.key
AND Lta.state in ('A','E')
WHERE Lta.key IS NULL

I am a little confused with those queries if you can give me some information related to this topic I will be so grateful to you

Thank you

Upvotes: 7

Views: 38609

Answers (2)

IVNSTN
IVNSTN

Reputation: 9299

For "not-existance" checking case I strongly recommend you to use not exists subquery:

SELECT * FROM TableA ta
WHERE not exists
  (
    SELECT 1 FROM TableA Lta 
    WHERE ta.key = Lta.key
      AND ta.state IN('C')
      AND Lta.state IN ('A','E')
  )

this is the most performance-friendly approach.

Not sure but it's likely that you should move ta.state = 'C' to the outer where clause.

Upvotes: 1

DRapp
DRapp

Reputation: 48139

You were very close in your first query. Move the "ta.state" to the where clause. The join is how the two tables relate but secondary criteria on JUST the "lta" alias.

SELECT 
      * 
   FROM 
      TableA ta
         LEFT JOIN TableA Lta 
            ON ta.key = Lta.key
           AND Lta.state IN ('A','E')
   WHERE 
          ta.state IN('C')
      AND Lta.key is null

So your primary criteria is WHERE the ta.state is "C", but then only if there is NOT a match for the "A" and "E" instances in the second (left-join) alias of lta

Upvotes: 10

Related Questions