回答

0

是的,你可以通过改变表,然后更新值做到这一点:

alter table table2 add column TagId int; 

update table2 t2 join 
     table1 t1 
     on t2.TagName = t1.TagName 
    set t2.TagId = t1.TagId; 

alter table table2 add constraint fk_table2_tagid 
    foreign key (TagId) references table1(TagId); 

我会建议在table1(TagName)建立索引的性能。

+0

我会在添加FK约束之前更新这些值。在更新之后,您仍然可能会发现一些由于最初没有FK而成为孤儿的记录。他们可能需要手动解决。 – HLGEM

+0

我不得不在添加外键约束之前更新这些值,因为它不会让我这样做。有道理,因为父表中没有任何ID是空的,当我尝试设置关系时,这显然引起了一个问题。 伙计们,非常感谢你的帮助! –

相关问题