簡體   English   中英

Sql Join從A表中選擇記錄和從B表中選擇符合條件的記錄

[英]Sql Join selecting records from A table and selecting matching records with a condition from B table

我們有表 A 和表 B,我們需要的數據在表 A 中,我們使用表 B 來驗證我們具有匹配 ID 的情況。 如果 ID 不匹配,我們可以 select 不驗證,但如果它們匹配,我們需要檢查日期是否在 date1 和 date2 之間。 如果它們在 A 中匹配,我們只檢查 B 中的記錄; (我們可以忽略表 B 中的 id=4,因為它不在 A 中); 而我們只需要A表的數據。

我花了太多時間創建 sql 到 select:

表 A 中不在表 B 中的所有內容(ids,fe id = 1,3),以及 select 匹配記錄,其中匹配記錄 A.date 在 B.date1 和 B.date2 之間(如果它匹配而不在之間)選擇)

TABLE A
id       date          col1
1       5/08/2021    11223344
2       15/06/2021   22334411
2       15/04/2021   22223344 
3       10/11/2021   22223311

TABLE B
id       date1         date2
5       5/08/2021     5/09/2021
2       15/05/2021    15/07/2021
2       15/08/2021    15/09/2021
4       15/08/2021    15/10/2021

結果應如下所示:

id       date          col1
1       5/08/2021    11223344
3       10/11/2021   22223311
2       15/06/2021   22334411

對您的問題的改進是在查詢中添加您的最后一次嘗試。 但據我了解,你的問題可以這樣解決:

SELECT A.ID, A.date, A.col1 FROM A
LEFT JOIN B ON A.id = B.id
WHERE (A.Date BETWEEN B.date1 AND b.date2) OR B.date1 IS NULL
  • LEFT JOIN保留表A的所有記錄
  • A.Date BETWEEN B.date1 AND b.date2根據你的條件過濾匹配的行
  • B.Date1 IS NULL來自 A 的行在 B 中沒有匹配項

因為你想保留A中滿足你條件的所有行——大概沒有重復——我建議使用exists和 `not exists:

select a.*
from a
where exists (select 1
              from b
              where a.id = b.id and
                    a.date between b.date1 and b.date2
             ) or
      not exists (select 1
                  from b
                  where a.id = b.id
                 );

如果b中有多個匹配行,則使用left join的解決方案可能會返回重復行。

暫無
暫無

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

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