简体   繁体   English

左连接到同一个表SQL

[英]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: 我试图在同一个查询中对同一个表进行左连接,但结果不是okey,我用子查询解决了这个问题,这是错误的查询:

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. 将“ta.state”移动到where子句。 The join is how the two tables relate but secondary criteria on JUST the "lta" alias. 连接是两个表的关系,但是次要标准就是“lta”别名。

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 所以你的主要标准是ta.state为“C”的地方,但是只有当lta的第二个(左连接)别名中的“A”和“E”实例不匹配时

For "not-existance" checking case I strongly recommend you to use not exists subquery: 对于“不存在”检查案例,我强烈建议您使用not exists子查询:

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. 不确定,但你可能应该将ta.state = 'C'移动到外部where子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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