我有桌子: T1 (ID BIGINT, NAME NVARCHAR(1000))
数据:
select * from T1
1, AAA
2, BBB
3, CCC
4, DDD
在RELATIONS_T
(ID, T1_ID1,T1_ ID2
)表保存之间的关系ID
从S”T1
表。
SELECT *
FROM RELATIONS_T
输出:
ID, T1_ID1,T1_ ID2
1, 1, 2
在此表中1连接到2
在RELATIONS_LOG_TABLE
(ID, OLD_ID, NEW_ID, OLD_STUFF_ID, NEW_STUFF_ID
)中的列OLD_STUFF_ID
和NEW_STUFF_ID
是不是我的问题很重要。
Select ID, OLD_ID, NEW_ID
from RELATIONS_LOG_TABLE
输出:
ID, OLD_ID, NEW_ID
1, 1, 3
2, 2, 4
这意味着1变成3,而2变成4
如何从表RELATIONS_LOG_TABLE和RELATIONS_T中检查1和2之间是否存在连接,并手动在表RELATIONS_T 3、4中输入。
以下语句将插入元组
3,2(1替换为3) 1,4(2替换为4) 3,4(均替换)
insert into relations_t (id1, id2)
select coalesce(rep1.new_id, id1), coalesce(rep2.new_id, id2)
from relations_t r
left join relations_log_table rep1 on rep1.old_id = r.id1
left join relations_log_table rep2 on rep2.old_id = r.id2
where rep1.id is not null or rep2.id is not null;
如果您只想要“最佳”记录(在这种情况下都被替换,否则被替换),则必须根据替换次数获得最高记录。
insert into relations_t (id1, id2)
select top(1) coalesce(rep1.new_id, id1), coalesce(rep2.new_id, id2)
from relations_t r
left join relations_log_table rep1 on rep1.old_id = r.id1
left join relations_log_table rep2 on rep2.old_id = r.id2
where rep1.id is not null or rep2.id is not null
order by case when rep1.id is not null and rep2.id is not null then 0 else 1 end;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句