简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM