如何在SQL中获得两个表的并集
假设我有两张桌子 表A:带有ID列和值 1. 2. 三, 表B:带有ID列和值 2. 3. 四, 我想要下表中的结果集 如果id是唯一的,则可以使用完全联接: 如果id不是唯一的,您可以向上面添加聚合。相反,我想我应该使用union all和group by:如何在SQL中获得两个表的并集,sql,oracle,Sql,Oracle,假设我有两张桌子 表A:带有ID列和值 1. 2. 三, 表B:带有ID列和值 2. 3. 四, 我想要下表中的结果集 如果id是唯一的,则可以使用完全联接: 如果id不是唯一的,您可以向上面添加聚合。相反,我想我应该使用union all和group by: 如果一个id在两个表中重复多次,这将防止过度处理。使用union和left join,您可以尝试如下操作 with cte as( select 1 as id union all select 2 union all select 3
如果一个id在两个表中重复多次,这将防止过度处理。使用union和left join,您可以尝试如下操作
with cte
as(
select 1 as id
union all
select 2
union all
select 3 )
,
cte2 AS
(
select 2 as id
union all
select 3
union all
select 4 )
, cte3 as (
select id from cte
union
select id from cte2
) select cte3.id, case when cte.id is null then 'NO' else 'Yes' end as prestnInA,
case when cte2.id is null then 'NO' else 'Yes' end as prestnInB
from cte3
left join cte on cte3.id=cte.id
left join cte2 on cte3.id=cte2.id
输出
id prestnInA prestnInB
1 Yes NO
2 Yes Yes
3 Yes Yes
4 NO Yes
如果id是PK,您可以使用下面的查询找到您的解决方案
select id,
(case when id in (select * from tableA) then 'YES' else 'NO' end) as PRESENTINA,
(case when id not in (select * from tableB) then 'NO' else 'YES' end) as PRESENTINB
from tableA
union
select id,
(case when id in (select * from tableA) then 'YES' else 'NO' end) As PRESENTINA,
(case when id not in (select * from tableB) then 'NO' else 'YES' end) as PRESENTINB
from tableB
id prestnInA prestnInB
1 Yes NO
2 Yes Yes
3 Yes Yes
4 NO Yes
select id,
(case when id in (select * from tableA) then 'YES' else 'NO' end) as PRESENTINA,
(case when id not in (select * from tableB) then 'NO' else 'YES' end) as PRESENTINB
from tableA
union
select id,
(case when id in (select * from tableA) then 'YES' else 'NO' end) As PRESENTINA,
(case when id not in (select * from tableB) then 'NO' else 'YES' end) as PRESENTINB
from tableB