【发布时间】:2021-03-16 21:42:59
【问题描述】:
为什么 EXCEPT 没有返回预期结果?我觉得这应该可行,但它返回零行。但是,如果我计算 T3 中不在 t2 中的 order-buid-tie 行,我会得到数千个结果,反之亦然。
人工审核
--first table (T3) without T2 match --178k
select count(*) --178K
from LAB3.Report_stg st3
left join LAB2.Report_stg st2
on st3.order_num = st2.order_num and st3.buid= st2.buid and st3.tie_nbr = st2.tie_num
where st2.tie_num is null
--second table (t2) without match in first (T3)
select count(*) --12.5M
from LAB2.Report_stg st2
left join LAB3.Report_stg st3
on st3.order_num = st2.order_num and st3.buid = st2.buid and st3.tie_num = st2.tie_num
where st3.tie_num is null
让我们试试 EXCEPT。我希望这里有 178k 行并得到零
--to avoid cartesian join
--select all mismatched tie_nums
--unless (EXCEPT if) that tie_num exists as a matched set between the two tables
select t3.order_num, t3.buid, t3.tie_num as t3_tie
from LAB3.Report_stg t3
left join LAB2.Report_stg t2
on t3.order_num = t2.order_num and t3.buid = t2.buid and t3.tie_num <> t2.tie_num
except
(select st3.order_num, st3.buid, st3.tie_num
from LAB3.Report_stg st3
left join LAB2.Report_stg st2
on st3.order_num = st2.order_num and st3.buid = st2.buid and st3.tie_num = st2.tie_num
)
【问题讨论】:
-
与
EXCEPT无关。您将谓词从ON ... st3.tie_nbr = st2.tie_num WHERE st2.Tie_num is null(反连接)更改为ON ... t3.tie_num <> t2.tie_num,这实际上使EXCEPT之前的部分变为内连接。 -
谢谢!我想到了。第二个子句必须是 INNER JOIN!
标签: sql join teradata diff except