如何用单条查询获取两张表中所有不匹配的行?
解决两表差异查询问题
你的查询只返回第一张表的行,问题出在where m.date = '2022-11-01'这个条件——当full outer join返回来自test2的无匹配行时,m的所有字段都是null,m.date自然不满足等于'2022-11-01'的条件,这些行被过滤掉了。
要找出两表中列值不完全匹配的行,同时限定日期为2022-11-01,且不用子查询,你可以用以下查询:
select m.*, t.* from test.test1 m full outer join test.test2 t on row(m) = row(t) where coalesce(m.date, t.date) = '2022-11-01' and row(m) is distinct from row(t);
关键说明:
full outer join:保留两张表中所有行,不管是否存在匹配项row(m) is distinct from row(t):过滤掉列值完全一致的行,同时正确处理字段为null的情况(比row(m) <> row(t)更严谨,因为null和任何值比较的结果都是unknown,而is distinct from会将null视为相等)coalesce(m.date, t.date) = '2022-11-01':确保只处理日期为2022-11-01的行,不管该行来自test1还是test2
如果你的需求是仅关注test1中date为2022-11-01的行与test2的差异,也可以调整为:
select m.*, t.* from test.test1 m full outer join test.test2 t on row(m) = row(t) where m.date = '2022-11-01' or (t.date = '2022-11-01' and m is null);
内容的提问来源于stack exchange,提问作者Miko
相关产品推荐
相关产品推荐

