我试图从两个表中获取唯一值,这两个表都只有一列称为域。
DDL:
create table domains_1 (domain varchar);
create table domains_2 (domain varchar);
DML:
insert into domains_1 values ('example_1.com'), ('example_2.com');
insert into domains_2 values ('example_2.com'), ('example_3.com');
有几种方法可以做到这一点,我决定使用完整的外部联接。
select case when a.domain is null then b.domain
when b.domain is null then a.domain
end as unique_domains
from domains_1 as a full outer join domains_2 as b on a.domain = b.domain;
令我惊讶的是,有null
在结果中除了独特的域之外。
我可以再添加一层select
排除空值,如下所示:
select * from
(select case when a.domain is null then b.domain
when b.domain is null then a.domain
end as unique_domains
from domains_1 as a full outer join domains_2 as b on a.domain = b.domain) t
where unique_domains is not null;
这怎么可以null
首先出现在结果中吗?
有没有更好的方法去除null
从结果来看?
Your CASE
表达式没有ELSE
,所以它默认为 null:
case when a.domain is null then b.domain
when b.domain is null then a.domain
ELSE NULL -- implicitly
end as unique_domains
值“example_2.com”具有匹配项,因此 a.domain 和 b.domain 都等于“example_2.com”且不为空。所以,两者WHEN
不匹配并且ELSE NULL
被申请;被应用。
至于“更好的方法”:我可能会使用
select coalesce(a.domain, b.domain) as domain
from domains_1 as a full outer join domains_2 as b on a.domain = b.domain
where a.domain is null or b.domain is null;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)