如何更改外键引用操作? (行为)

我已经设置了一个表,其中包含一个具有外键的列,设置为 ON DELETE CASCADE(删除父节点时删除子节点)

What would the SQL command be to change this to ON DELETE RESTRICT? (can't delete parent if it has children)

162490 次浏览
ALTER TABLE DROP FOREIGN KEY fk_name;
ALTER TABLE ADD FOREIGN KEY fk_name(fk_cols)
REFERENCES tbl_name(pk_names) ON DELETE RESTRICT;

旧的问题,但增加答案,以便一个人可以得到帮助

它的两个步骤过程:

假设,table1有一个 外键,列名为 fk_table2_id约束名为 fk_nametable2是关键字 t2(像下面这样的东西在我的图表中)的引用表。

   table1 [ fk_table2_id ] --> table2 [t2]

第一步 ,降低老限制: (参考文献)

ALTER TABLE `table1`
DROP FOREIGN KEY `fk_name`;

通知约束被删除,列不会被删除

第二步 ,添加新的限制:

ALTER TABLE `table1`
ADD CONSTRAINT `fk_name`
FOREIGN KEY (`fk_table2_id`) REFERENCES `table2` (`t2`) ON DELETE CASCADE;

添加约束后,column 已经存在

示例:

我有一个 UserDetails表指的是 Users表:

mysql> SHOW CREATE TABLE UserDetails;
:
:
`User_id` int(11) DEFAULT NULL,
PRIMARY KEY (`Detail_id`),
KEY `FK_User_id` (`User_id`),
CONSTRAINT `FK_User_id` FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`)
:
:

第一步:

mysql> ALTER TABLE `UserDetails` DROP FOREIGN KEY `FK_User_id`;
Query OK, 1 row affected (0.07 sec)

Second step:

mysql> ALTER TABLE `UserDetails` ADD CONSTRAINT `FK_User_id`
-> FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`) ON DELETE CASCADE;
Query OK, 1 row affected (0.02 sec)

结果:

mysql> SHOW CREATE TABLE UserDetails;
:
:
`User_id` int(11) DEFAULT NULL,
PRIMARY KEY (`Detail_id`),
KEY `FK_User_id` (`User_id`),
CONSTRAINT `FK_User_id` FOREIGN KEY (`User_id`) REFERENCES
`Users` (`User_id`) ON DELETE CASCADE
:

You can do this in one query 如果 you're willing to change its name:

ALTER TABLE table_name
DROP FOREIGN KEY `fk_name`,
ADD CONSTRAINT `fk_name2` FOREIGN KEY (`remote_id`)
REFERENCES `other_table` (`id`)
ON DELETE CASCADE;

如果您有一个很大的表,这对于减少停机时间很有用。

Remember that MySQL keeps a simple index on a column after deleting foreign key. So, if you need to change 'references' column you should do it in 3 steps

  • 放下原版 FK
  • 删除索引(使用 drop index子句,名称与前面的 fk 相同)
  • 创造新的 FK

您可以简单地使用一个查询来规则它们: 更改表格产品 删除外键 oldConstraintName, 在 DELETE CASCADE ON UPDATE CASCADE 上添加 FOREIGN KEY (product _ id,type _ id) REFERENCES FOREIGN alTableName (FOREIGN _ KEY _ name,another _ one _ makes _ Composite _ KEY)

我有一堆 FK 要修改,所以我写了一些东西,让我的声明。我觉得我应该分享一下:

SELECT


CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
'` DROP FOREIGN KEY `' ,rc.CONSTRAINT_NAME,'`;')
, CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
'` ADD CONSTRAINT `' ,rc.CONSTRAINT_NAME ,'` FOREIGN KEY (`',kcu.COLUMN_NAME,
'`) REFERENCES `',kcu.REFERENCED_TABLE_NAME,'` (`',kcu.REFERENCED_COLUMN_NAME,'`) ON DELETE CASCADE;')


FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
LEFT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
ON kcu.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA
AND kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
WHERE DELETE_RULE = 'NO ACTION'
AND rc.CONSTRAINT_SCHEMA = 'foo'