如果 id 相同,联合替换行

Union replacing row if id is the same

我有 2 个具有相同数据结构的不同 table,table A 和 B,是否可以从 A 和 B 获取值,如果 B 中存在 ID 条目,它会替换A 中得到的值?

示例:

select '1' as id, 'Bob' as "user" from dual
union
select '1' as id, 'Alice' as "user" from dual

这个returns:

1   Bob
1   Alice

如果第二个 id 相同 select 我希望只有一行:

1   Alice

您需要“FULL OUTER JOIN”而不是 UNION,这将为您提供三种类型的行:

  • 行,其中两个 tables 都有匹配的 id,值来自两个 tables(INNER JOIN 会 return 的行)
  • 只有 table A 具有该 ID 的行,table B 的列为空(LEFT OUTER JOIN 会 return 的附加行)
  • 只有 table B 具有该 ID 的行,table A 的列为空(RIGHT OUTER JOIN return 的附加行)

然后您可以使用 COALESCE 从 B(如果存在)(第一种和第二种类型的行)和 A(如果不存在)(第三种类型的行)中获取值。

所以对于你的例子:

Select
    Coalesce(B.id, A.id) as id,
    Coalesce(B."user", A."user") as "user"
From
    (select '1' as id, 'Bob' as "user" from dual) as A
Full Outer Join
    (select '1' as id, 'Alice' as "user" from dual) as B
    On B.id = A.id

哪个 returns:

id user
1 Alice

(注意:在 SQL 服务器上测试,通过删除“from dual”,因为我没有要测试的 Oracle 数据库。)

一种方法是:

select '1' as id, 'Bob' as "user" from table_A
where id not in (select id from table_B)
union all
select '1' as id, 'Alice' as "user" from table_B

您可以尝试使用 ROW_NUMBER() over (PARTITION BY id order by tab) 其中“tab”是 table 名称,在此示例中,来自 table_a 的数据将获得优先权并被拾取。

create table table_a as 
(
select '1' as id, 'Bob' as "user" from dual
UNION
select '2' as id, 'Jack' as "user" from dual
) ;

create table table_b as 
(
select '1' as id, 'Alice' as "user" from dual -- table 
UNION
select '3' as id, 'John' as "user" from dual -- table
) ;

select * from (
select ROW_NUMBER() over (PARTITION BY id order by tab) rnum,id, "user"
 from( 
select id, "user", 'A' tab from table_a 
union all
select id, "user", 'b' tab from table_b  
) 
) WHERE RNUM = 1;