使用WHERE类的SQL LEFT JOIN

时间:2016-10-27 10:53:57

标签: sql

TABLE1中有两个表TABLE1和TABLE2,在TABLE2中不存在以下左连接的记录我想查询TABLE1中的所有记录,如果table2中不存在该记录的话。

注意:关于我需要的代码中的WHERE类,这是因为,在TABLE2中,“IN PROGRESS”名称中可能有几条记录,其中一条记录的名称为“GRADUATED”我想基于的不同记录表1 ID,如果'GRADUATE'的名称中有任何记录,它应该只显示它​​应该显示在进展中的其他记录。

SELECT DISTINCT 
       TABLE1.ID, 
       TABLE2.TRAINING_STATUS_CHECK
FROM TABLE1
LEFT JOIN TABLE2
    ON TABLE1.ID = TABLE2.FK_ID_CLASS
WHERE NOT EXISTS 
    (
    SELECT DISTINCT 
           TABLE1.ID, 
           TABLE2.TRAINING_STATUS_CHECK
    FROM TABLE1
    LEFT JOIN TABLE2
        ON TABLE1.ID = TABLE2.FK_ID_CLASS
    WHERE TABLE2.TRAINING_STATUS_CHECK = 'GRADUATED')
OR TABLE2.TRAINING_STATUS_CHECK = 'GRADUATED'

5 个答案:

答案 0 :(得分:2)

表格之间的关系不存在 - 但仅当比较涉及表格中没有“毕业”的行时才会出现。 (我认为)

SELECT DISTINCT 
       TABLE1.ID, 
       TABLE2.TRAINING_STATUS_CHECK
FROM TABLE1
LEFT JOIN TABLE2 ON TABLE1.ID = TABLE2.FK_ID_CLASS
   AND TABLE2.TRAINING_STATUS_CHECK <> 'GRADUATED'
WHERE TABLE2.FK_ID_CLASS IS NULL

答案 1 :(得分:2)

我看到你的查询存在一些可能性:

  1. 存在部分与您的主查询无关。我认为你需要一些关系
  2. 不存在部分不存在
  3. 您使用与过滤器主行集
  4. 相同的条件过滤列

    据我所知,你想从table1获取所有行,状态为'GRADUATED'int table2,table1中的任何行,其中table2中的行不存在或状态不等于'GRADUATED'

    SELECT DISTINCT 
           t1.ID, 
           t2.TRAINING_STATUS_CHECK
    FROM TABLE1 t1
    LEFT JOIN TABLE2 t2 ON t1.ID = t2.FK_ID_CLASS
    WHERE NOT EXISTS 
        (
        SELECT NULL /*its not nesessary what you need*/
        FROM TABLE1 sub_t1
        JOIN TABLE2 sub_t2 ON sub_t1.ID = sub_t2.FK_ID_CLASS /* left join replaced to inner */
        WHERE sub_t2.TRAINING_STATUS_CHECK = 'GRADUATED'
          AND sub_t1.ID = t1.ID /*relation with outer query*/
        )
    OR t2.TRAINING_STATUS_CHECK = 'GRADUATED'
    

答案 2 :(得分:1)

不确定您的问题,但如果您想要表1中不在表2中的所有记录,您只需要这样做:

SELECT TABLE1.ID
FROM TABLE1 
LEFT JOIN TABLE2 ON TABLE1.ID = TABLE2.FK_ID_CLASS
WHERE TABLE2.FK_ID_CLASS IS NULL

答案 3 :(得分:1)

试试这个:

SELECT DISTINCT TABLE1.ID, TABLE2.TRAINING_STATUS_CHECK
  FROM TABLE1
  LEFT JOIN TABLE2
    ON TABLE1.ID = TABLE2.FK_ID_CLASS
   AND (NOT EXISTS (SELECT 1
                    FROM  TABLE2 t
                    WHERE TABLE1.ID = t.FK_ID_CLASS
                      AND t.TRAINING_STATUS_CHECK = 'GRADUATED')
        OR TABLE2.TRAINING_STATUS_CHECK = 'GRADUATED')

对于记录,LEFT JOIN右表上的条件需要放在ON()子句中,否则由于INNER JOIN,联接将转移到NULL比较。

答案 4 :(得分:0)

在我看来,您可以使用OR将三个不同的案例“UNION组合在一起”;就个人而言,我发现保持三者分开,这样可以更容易阅读和理解:

--- ID with GRADUATED exists in TABLE2
( SELECT ID, 'GRADUATED' AS TRAINING_STATUS_CHECK
    FROM TABLE1
  INTERSECT 
  SELECT FK_ID_CLASS, 'GRADUATED'
    FROM TABLE2
  WHERE TRAINING_STATUS_CHECK = 'GRADUATED' )

UNION

--- ID without GRADUATED exists in TABLE2
( SELECT ID, 'IN PROGRESS'
    FROM TABLE1
  MINUS
  SELECT FK_ID_CLASS, 'IN PROGRESS'
    FROM TABLE2
   WHERE TRAINING_STATUS_CHECK = 'GRADUATED' )

UNION

--- ID does not exist in TABLE2
( SELECT ID, '{{NONE}}'
    FROM TABLE1
   WHERE ID NOT IN ( SELECT FK_ID_CLASS FROM TABLE2 ) );