如何在MySQL中对外键使用RESTRICT?


11

在数据库结构中

  CREATE TABLE Country (
  name varchar(40) NOT NULL,
  PRIMARY KEY  (name)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

CREATE TABLE City (
  name varchar(40) NOT NULL,
  PRIMARY KEY  (name)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

CREATE TABLE Map (
  country varchar(40) NOT NULL,
  city varchar(100) NOT NULL,
  PRIMARY KEY  (country,city),
  FOREIGN KEY (country) REFERENCES Country (name) ON DELETE CASCADE,
  FOREIGN KEY (city) REFERENCES City (name) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我希望City通过这三个相等的命令完整保留子级中的相应值来删除父级

  FOREIGN KEY (city) REFERENCES City (name) ON DELETE NO ACTION
  FOREIGN KEY (city) REFERENCES City (name) ON DELETE RESTRICT
  FOREIGN KEY (city) REFERENCES City (name)

但是当使用NO ACTIONOR RESTRICT或省略时ON DELETE。MySQL不允许我从父列中删除此错误:

ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails 
('test'.'Map', CONSTRAINT 'Map_ibfk_2' FOREIGN KEY ('city') REFERENCES 'City'('name')
 ON DELETE RESTRICT

我哪里错了?SQL的责任是NO ACTION删除父级并留下子级孤儿吗?

Answers:


13

根据有关删除约束MySQL文档

•RESTRICT:拒绝父表的删除或更新操作。指定RESTRICT(或NO ACTION)与省略ON DELETE或ON UPDATE子句相同。

至于不采取行动

•NO ACTION:标准SQL中的关键字。在MySQL中,等同于RESTRICT。如果被引用的表中有相关​​的外键值,InnoDB将拒绝父表的删除或更新操作。某些数据库系统具有延迟检查,而“ NO ACTION”是延迟检查。在MySQL中,立即检查外键约束,因此NO ACTION与RESTRICT相同。

DELETE RESTRICT可以保护父级而不是子级删除。


5

如果要删除父母并留下孩子,则可能需要以下ON DELETE SET NULL选项:

SET NULL:从父表中删除或更新该行,并将子表中的一个或多个外键列设置为NULL。ON DELETE SET NULL和ON UPDATE SET NULL子句均受支持。

如果指定SET NULL操作,请确保尚未将子表中的列声明为NOT NULL。

最后一句中有很多“ not”,因此只需确保parent_id 可以为NULL。

另请参阅以下相关问题:删除/更新外键约束中SET NULL的目的是什么?

通过定义外键,您已告知数据库不接受子表中在父表中没有相应值的条目。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.