我有一个表,我需要知道从前一天到今天的数据已更新。假设前几天数据在T1中,当前一天的数据在T2中,我尝试在所有列上进行" T1 Full Outer Join T2"(因为我需要在整个表上获得更新,而不论其任何列如何)。
问题是,如果T1中的一行在其任何列中都有零值,即使行中的行仍然相同,它也会导致输出,我不想要。这是我情况的一个例子。
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)
输出为:
主机位置OS---------------------------------------null null nullHOST3 Location3 Solarishost4 location4 WindowsHOST5 NULL LINUX
在预期的结果中需要删除host5,因为两个表中都存在同一行。
我了解这是由于全部条件和数据中的零值的全部结合的性质。只想知道是否有其他选择仅获取更新的记录。
有一个查看以外的地方,看看它是否适合您的需求
SELECT *
FROM t1
EXCEPT
SELECT *
FROM t2
输出:
Host location OS
--------------------------------
Host3 Location3 Solaris
Host4 Location4 Windows
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
将为您提供T1,而不是T2
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
将为您提供T2,而不是T1