[英]How do I implement a second non-unique identifier without concurrency issues?
[英]SQL: How do I combine tables on a single but non-unique identifier?
我有两个表:
TABLE 1 ID Value ValueFromTable2 1 A NULL 1 B NULL 1 C NULL 1 D NULL 2 E NULL 2 F NULL TABLE 2 ID Value 1 A1 1 A2 1 A3 2 BOB 2 JIM
我想用表2的值更新表1,以便产生以下行:
TABLE 1 ID Value ValueFromTable2 1 A A1 1 B A2 1 C A3 1 D NULL 2 E BOB 2 F JIM
命令它不是非常重要。 也就是说,我不担心A与A1配对或B与A2配对。 我只需要表2中“值”列中的全套数据即可从表1中获得。
请指教!
您需要一个密钥才能加入他们。 隐式键是排序。 您可以使用row_number()
显式添加:
select coalesce(t1.id, t2.id) as id,
t1.value, t2.value
from (select t1.*, row_number() over (partition by id order by (select NULL)) as seqnum
from table1 t1
) t1 full outer join
(select t2.*, row_number() over (partition by id order by (select NULL)) as seqnum
from table2 t2
) t2
on t1.id = t2.id and t1.seqnum = t2.seqnum;
通过使用full outer join
,无论哪个列表较长,所有值都会出现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.