簡體   English   中英

我可以追溯添加外鍵ID列並用另一個表的主鍵的值填充它,而不必手動輸入嗎?

[英]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與和填充它TagIDstable1 ,其中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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM