SQL Server:查询以获取表增量更新

时间:2016-12-29 19:33:45

标签: sql-server null full-outer-join

我有一张表,我需要知道从前一天到今天哪些数据已更新。假设前几天数据在t1中,而当前日数据在t2中,我试图做" t1 FULL OUTER JOIN t2"在所有列上(因为我需要在整个表上获得更新而不管任何列)t2的每列都是NULL。

问题是如果t1中的一行在其任何列中都有空值,即使行在t2中保持相同,也会产生输出,这是我不想要的。这是我的情况的一个例子。

create table t1(Host varchar(20), location varchar(20), OS varchar(20))
create table t2(Host varchar(20), location varchar(20), OS varchar(20))

  insert into t1 (Host,location,OS)
    values ('Host1','Location1','Linux'),
            ('Host2','Location2','Unix'),
            ('Host3','Location3','Solaris'),
            ('Host4','Location4','Windows'),
            ('Host5',null,'linux') ---> Host5 remains same in both tables

  insert into t2 (Host,location,OS)
    values ('Host1','Location1','Linux'),
            ('Host2','Location2','Unix'),
            ('Host3','Location3','Windows'),
            ('Host4','Location7','Windows'),
            ('Host5',null,'linux') ---> Host5 remains same in both tables

查询:

  SELECT distinct t1.Host, t1.location, t1.OS
  FROM t1 FULL OUTER JOIN
  t2 ON t1.Host = t2.Host 
         AND t1.location = t2.location 
         AND t1.OS = t2.OS
  WHERE (t2.Host IS NULL) OR
        (t2.location IS NULL) OR
        (t2.OS IS NULL)

输出结果为:

Host    location    OS
---------------------------
NULL    NULL        NULL
Host3   Location3   Solaris
Host4   Location4   Windows
Host5   NULL        linux 

在预期结果中,需要删除Host5,因为表中存在相同的行。

我理解这是由于FULL OUTER JOIN的性质与WHERE条件和数据中的NULL值。只是想知道是否有任何替代方法只能获取更新的记录。

2 个答案:

答案 0 :(得分:1)

查看EXCEPT,看看它是否符合您的需求

SELECT *
FROM t1
EXCEPT 
SELECT *
FROM t2  

输出:

Host    location    OS 
--------------------------------
Host3   Location3   Solaris 
Host4   Location4   Windows

答案 1 :(得分:0)

SELECT distinct t1.Host, t1.location, t1.OS
FROM t1
LEFT JOIN t2 ON 
   t1.Host = 2.Host AND
   COALESCE(t1.location,'<<null>>') = COALESCE(t2.location,'<<null>>') AND 
   t1.OS = t2.OS
WHERE COALESCE(t2.Host,t2.location,t2.OS) is null

不会在t2中给你t1

SELECT distinct t2.Host, t2.location, t2.OS
FROM t2
LEFT JOIN t1 ON t1.Host = t2.Host AND t1.location = t2.location AND t1.OS = t2.OS
WHERE COALESCE(t1.Host,t1.location,t1.OS) is null

不会在t1中给你t2