如何使用表中的新ID将关系从一个表转移到另一个表

时间:2014-04-28 10:00:50

标签: sql sql-server sql-server-2012 relation

我有桌子:T1 (ID BIGINT, NAME NVARCHAR(1000))

数据:

select * from T1
1, AAA
2, BBB
3, CCC
4, DDD

RELATIONS_TID, T1_ID1,T1_ ID2)表格保存ID表格T1之间的关系。

SELECT * 
FROM RELATIONS_T

输出:

ID, T1_ID1,T1_ ID2
1,    1,   2 

在此表1中连接到2

RELATIONS_LOG_TABLEID, OLD_ID, NEW_ID, OLD_STUFF_ID, NEW_STUFF_ID)列OLD_STUFF_IDNEW_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中手动输入。

1 个答案:

答案 0 :(得分:0)

以下语句将插入元组

3,2 (1 replaced by 3)
1,4 (2 replaced by 4)
3,4 (both replaced)
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;