如何更改外键引用操作? (行为)
我已经设置了一个表,其中包含带有外键的列,设置为 ON DELETE CASCADE(删除父级时删除子级)将
其更改为 ON DELETE 的 SQL 命令是什么限制? (如果父级有子级,则无法删除)
I have set up a table that contains a column with a foreign key, set to ON DELETE CASCADE
(delete child when parent is deleted)
What would the SQL command be to change this to ON DELETE RESTRICT
? (can't delete parent if it has children)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
老问题,但添加答案以便获得帮助
它的两步过程:
假设,
table1
有一个外键 列名为fk_table2_id
,约束 名称为fk_name
,table2
是带有键t2 的引用表
(如下图所示)。第一步,删除旧约束:(参考)
注意约束已删除,列未删除
第二步,添加新约束:
添加约束,列已存在
示例:
我有一个
UserDetails
表引用Users
表:第一步:
第二步:结果
:
Old question but adding answer so that one can get help
Its two step process:
Suppose, a
table1
has a foreign key with column namefk_table2_id
, with constraint namefk_name
andtable2
is referred table with keyt2
(something like below in my diagram).First step, DROP old CONSTRAINT: (reference)
notice constraint is deleted, column is not deleted
Second step, ADD new CONSTRAINT:
adding constraint, column is already there
Example:
I have a
UserDetails
table refers toUsers
table:First step:
Second step:
result:
如果您愿意更改其名称,则可以在一个查询中执行此操作:
如果您有一张大型表,这对于最大限度地减少停机时间非常有用。
You can do this in one query if you're willing to change its name:
This is useful to minimize downtime if you have a large table.
请记住,MySQL 在删除外键后会在列上保留一个简单索引。因此,如果您需要更改“引用”列,您应该分 3 个步骤进行:
drop index
子句)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
drop index
clause)我有很多 FK 需要修改,所以我写了一些东西来为我做这些声明。我想我会分享:
I had a bunch of FKs to alter, so I wrote something to make the statements for me. Figured I'd share:
您可以简单地使用一个查询来规则所有这些:
<代码>
更改表产品
删除外键旧约束名称,
添加外键(product_id,category_id)引用externalTableName(foreign_key_name,another_one_makes_composite_key)在删除级联上更新级联
You can simply use one query to rule them all:
ALTER TABLE products
DROP FOREIGN KEY oldConstraintName,
ADD FOREIGN KEY (product_id, category_id) REFERENCES externalTableName (foreign_key_name, another_one_makes_composite_key) ON DELETE CASCADE ON UPDATE CASCADE