繁体   English   中英

在字段中具有空值的情况下,在两个表之间比较数据而没有除运算符

[英]Comparing data between two tables without except operator when having null values in fields

我在SQL Server中有此查询,这将给我两个表之间的区别

SELECT * FROM dbo.emp
except
SELECT * FROM #temp1

我只用一条记录就得到了正确的结果(正确)

但是当我使用左外部联接时

SELECT emp.* FROM emp
LEFT JOIN #temp1 ON emp.empid = #temp1.empid 
and
emp.firstname = #temp1.firstname 
AND emp.lastname = #temp1.lastname 
and emp.salary = #temp1.salary
and emp.dob = #temp1.dob
WHERE #temp1.empid IS NULL;

我得到39条记录。 为什么会有所不同? 我在加入条件中提到了所有列。

我知道如何通过where子句执行此操作,但我的目的是了解为什么外部联接不起作用。 基本上我做错了什么

下面的代码有效

SELECT dbo.emp.* FROM dbo.emp
JOIN #temp1 ON emp.empid = #temp1.empid 
where
emp.firstname <> #temp1.firstname 
or emp.lastname <> #temp1.lastname 
or emp.salary <> #temp1.salary
or emp.dob <> #temp1.dob;

外连接可能不起作用,因为某些字段具有NULL值。

您可以使用union allgroup by来模拟except

SELECT emp.*
FROM ((select 'emp' as which, empid, firstname, lastname, salary, dob
       from emp
      ) union all
      (select 'temp', empid, firstname, lastname, salary, dob
       from @temp1
      )
     ) t
group by empid, firstname, lastname, salary, dob
having sum(case when which = 'temp' then 1 else 0 end) = 0;

编辑:

您可以使用更复杂的条件通过join执行此操作:

SELECT emp.*
FROM emp LEFT JOIN
     #temp1
     ON (emp.empid = #temp1.empid or coalesce(emp.empid, #temp1.empid) is null) and
        (emp.firstname = #temp1.firstname or coalesce(emp.firstname, #temp1.firstname) is null) and
        (emp.lastname = #temp1.lastname or coalesce(emp.lastname, #temp1.lastname) is null)  and
        (emp.salary = #temp1.salary or coalesce(emp.salary,  #temp1.salary) is null) and
        (emp.dob = #temp1.dob or  or coalesce(emp.dob, #temp1.dob ) is null)
WHERE #temp1.empid IS NULL;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM