簡體   English   中英

SQL Server-從LEFT表返回所有記錄,而從右表僅返回不匹配的記錄

[英]SQL Server - Return all records from LEFT table and only non matching records from right table

我有2個具有相同結構(表名)的表。 表1和表2。

我需要返回表1中的所有記錄,並且僅返回表2中與表1中的記錄不匹配/聯接的記錄。

表2比表1具有更多的記錄。

我將加入3個字段中的2個表。

因此,基本上我希望返回table1的所有記錄,並且只返回與table2的table1不匹配(在3個字段上連接)的記錄。

換句話說,當兩個表中都存在記錄時,表1記錄的優先級高於最終結果輸出中的表2記錄(3個字段的值相同)

我開始寫類似下面的內容,但我認為它不起作用。 我應該改用左外部聯接嗎?

    Select * from table1 t1
    left join table2 t2 on t1.id = t2.id and t1.date = t2.date and t1.custid= t2.custid
where t2.id is null or t2.date is null or t2.custid is null

因此,您需要table1每一行以及table2中與table1不匹配的行?

SELECT *
FROM table1
UNION ALL
SELECT *
FROM table2 t2
WHERE NOT EXISTS(SELECT * FROM table1
                 WHERE id = t2.id
                 AND date = t2.date
                 AND custid = t2.custid);
Select * from table1 t1
  Union
Select * from table2 t2
Where Not exists
     (Select * from table1 
      Where id = t1.id 
         and date = t1.date 
         and custid= t1.custid)

暫無
暫無

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

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