首页 文章

SQL Server - 返回LEFT表中的所有记录,只返回右表中的非匹配记录

提问于
浏览
0

我有2个具有相同结构的表(字段名称) . 表1和表2 .

我需要返回Table1中的所有记录,并且只返回Table2中与Table1中的记录不匹配/连接的记录 .

Table2的记录多于Table1 .

我正在加入3个领域的2个表 .

所以基本上我希望返回table1中的所有记录,只返回没有匹配(在3个字段上连接)到table2的table1的记录 .

换句话说,当两个表中都存在记录时,Table1记录优先于我的最终结果输出中的table2记录(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

2 回答

  • 2
    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)
    
  • 2

    那么,您需要 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);
    

相关问题