[英]Can I retroactively add a foreign key ID column and populate it with the values of another table's primary key without having to enter manually?
我有兩個表:
Table1 (TagID, TagName, Primary Key (TagID)<br>
Table2 (TagName,ProductName, ProductID)
我想一個加TagID
列於Table2
與和填充它TagIDs
從table1
,其中TagName=TagName
。
是否可以不通過單獨輸入TagID來實現?
是的,您可以通過更改表然后更新值來做到這一點:
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)
上建立索引以提高性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.