具有单独 ID 的 SQL 联接表

  • 本文关键字:SQL 单独 ID sql oracle
  • 更新时间 :
  • 英文 :


对于这些表:

表 a

id | val 
---+-------
1  | foo
2  | bar
3  | spam 

表 b

id | val 
---+-------
1  | foo
2  | bar
4  | eggs 

表 c

id | val 
---+-------
0  | gaa
2  | bar
3  | spam

如何执行连接,使 id 列包含所有 3 个表的列表?那是:

id | val 
---+-------
0  | gaa
1  | foo
2  | bar
3  | spam
4  | eggs 
  • 对于基本方案,如果同一id没有不同的val,请使用 UNION
  • 如果您对同一id有不同的val,则需要使用一些逻辑来删除它们,如下所示:

--

select id, val from
(select t.*, row_number() over (partition by id order by num) as rn from 
(select id, val, 1 as num -- number to add logic from to give priority to the data of table
from a
union all -- duplicate do not need to be removed as we handle it using analytical function 
select id, val, 2
from b
union all
select id, val, 3
from c) t)
where rn = 1;

上面的查询将始终给出idval的表a数据,如果同一ID有不同的val

干杯!!

union怎么样?

select id, val
from a
union   -- on purpose to remove duplicates
select id, val
from b
union 
select id, val
from c;

这将删除重复项。

如果 val 可能会更改,并且您想要"第一个"表中的值,那么您可以检查一下:

select id, val
from a
union all
select id, val
from b
where not exists (select 1 from b where b.id = a.id)
union all
select id, val
from c
where not exists (select 1 from a where c.id = a.id) and
not exists (select 1 from b where c.id = b.id);

如果id上有索引(假设它是主键(,那么这可能比使用union的第一个版本更快。

最新更新