[英]Update primary key in one table which is foreign key in another table
I have a table that it's primary key is foreign key in 5 tables.I need to change the value of this primary key field.what's the query?我有一个表,它的主键是 5 个表中的外键。我需要更改这个主键字段的值。查询是什么?
Table1 >> fields: tbl1ID(pk, bigint), Desc(nvarchar(50))
Table2 >> fields: tbl2ID(pk, bigint),tbl1ID(fk, bigint), Desc(nvarchar(50))
Table3 >>....
.
.
.
I've set tbl1ID=1 and now i need to change it like this tbl1ID=100001, but i cant because this field is related to another table.我已经设置了 tbl1ID=1,现在我需要像这样更改 tbl1ID=100001,但是我不能,因为这个字段与另一个表相关。
is it possible to change all of them?是否有可能改变所有这些?
You can do this simply by temporarily setting foreign_key_checks=0 in your session.您可以通过在会话中临时设置 foreign_key_checks=0 来完成此操作。
SET FOREIGN_KEY_CHECKS = 0;
UPDATE TABLE_A INNER JOIN TABLE_B ON TABLE_B.PKID = TABLE_A.PKID
SET TABLE_B.PKID = 'NEW_VALUE', TABLE_A.PKID = 'NEW_VALUE'
WHERE TABLE_A.PKID = 'OLD_VALUE';
Another option is to configure the foreign key with the ON UPDATE CASCADE option so that if the primary key is updated on the parent table it will cascade to the child table另一种选择是使用 ON UPDATE CASCADE 选项配置外键,这样如果主键在父表上更新,它将级联到子表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.