簡體   English   中英

SQL LEFT JOIN 從第二個表中排除兩條記錄

[英]SQL LEFT JOIN EXCLUDE TWO RECORDS FROM SECOND TABLE

我正在嘗試 LEFT join 並且還想從第二個表中排除記錄,如果 status=Yes。 但是當我使用 LEFT join 時,它會給出 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 的狀態為“是”。

我知道我的 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

您需要在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'

請參閱演示
結果:

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

如果要過濾記錄,請使用內部聯接,而不是外部聯接:

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'
                 );

您可以通過使用NOT EXISTS條件來解決問題,例如:

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

另一個查詢如下(因為我真的不明白為什么它也需要加入 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

試試這個

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

我會這樣寫解決方案:

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 中沒有匹配項的行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM