SQL左联接从第二个表中排除两个记录

时间:2020-09-20 15:18:03

标签: mysql sql left-join

我正在尝试向左联接,并且如果status = Yes,也想从第二个表中排除记录。但是,当我使用LEFT连接时,它将提供table1中的所有记录,而不会排除table2中状态为“是”的记录。

Table1
--------------------------------
id  date
--------------------------------
1   01/09/2020
2   02/09/2020
3   03/09/2020
4   04/09/2020
5   05/09/2020


Table2
--------------------------------
id  date          status
--------------------------------
1   01/09/2020    Yes
2   02/09/2020    Yes
3   03/09/2020

所需结果

--------------------------------
id  date
--------------------------------
3   03/09/2020   
4   04/09/2020   
5   05/09/2020

排除ID 1,2,因为table2的状态为=“ yes”。

我知道我的SQL语法错误。请告知正确的语法:

SELECT table1.id,table1.date
FROM table1
LEFT JOIN (select table2.id, table2.date from table2 where status!='Yes') as table2
ON table1.id=table2.id and table1.date = table2.date

6 个答案:

答案 0 :(得分:2)

您需要在WHERE子句中设置正确的条件:

SELECT t1.*
FROM Table1 t1 LEFT JOIN Table2 t2
ON t2.id = t1.id AND t2.date = t1.date
WHERE COALESCE(t2.status, '') <> 'Yes'

或:

SELECT t1.*
FROM Table1 t1 LEFT JOIN Table2 t2
ON t2.id = t1.id AND t2.date = t1.date
WHERE t2.status IS NULL OR t2.status <> 'Yes'

请参见demo
结果:

> id | date      
> -: | :---------
>  3 | 03/09/2020
>  4 | 04/09/2020
>  5 | 05/09/2020

答案 1 :(得分:1)

如果要过滤记录,则使用内部联接,而不是外部联接:

SELECT t1.id, t1.date
FROM table1 t1 JOIN
     table2 t2
     ON t1.id = t2.id and t1.date = t2.date
WHERE t2.status <> 'Yes';

编辑:

根据您的评论,我认为NOT EXISTS是最好的方法:

select t1.*
from table1 t1
where not exists (select 1
                  from table2 t2
                  where t1.id = t2.id and t1.date = t2.date and
                        t2.status = 'Yes'
                 );

答案 2 :(得分:1)

您可以使用NOT EXISTS这样的条件来解决问题:

SELECT Table1.*
FROM Table1
WHERE NOT EXISTS (
    SELECT id FROM Table2 WHERE Table2.id = Table1.id AND Table2.status = 'Yes'
);

答案 3 :(得分:0)

以下是一个替代查询(因为我真的不明白为什么也需要加入id):

SELECT `t1`.`id`,`t1`.`date` FROM `Table1` `t1` 
LEFT JOIN `Table2` `t2` ON `t1`.`date`=`t2`.`date`
WHERE `t2`.`status` <> 'Yes' OR `t2`.`date` IS NULL;

这里是相关的SQLFiddle

答案 4 :(得分:0)

尝试一下

SELECT t1.* 
FROM Table1 t1 
LEFT JOIN Table2 t2 ON t2.id = t1.id 
WHERE t2.status != 'Yes' 
GROUP BY t1.id;

答案 5 :(得分:0)

我会这样写解决方案:

SELECT Table1.id, Table1.date
FROM Table1 LEFT OUTER JOIN Table2
  ON Table1.id = Table2.id AND Table2.status = 'Yes'
WHERE Table2.id IS NULL

您知道,如果没有匹配项,则左外部联接将为右表的行返回NULL。如果匹配条件包括status='Yes',则具有其他状态值的行不匹配。

然后WHERE子句将结果限制为Table1中不匹配的行。