简体   繁体   English

MYSQL外键ON DELETE和ON UPDATE

[英]MYSQL Foreign Key ON DELETE and ON UPDATE

I have a website which has a users table and a movies table. 我有一个网站,其中有一个用户表和一个电影表。 I am creating a favourites table so that users can save movies to their favourites list. 我正在创建收藏夹表,以便用户可以将电影保存到他们的收藏夹列表中。 The question is concerning the favourites table which I have been adviced to use the below : 这个问题与我建议使用以下收藏夹表有关:

CREATE TABLE Favorites (
  user_id INT NOT NULL,
  movie_id INT NOT NULL,
  PRIMARY KEY (user_id, movie_id),
  FOREIGN KEY (user_id) REFERENCES Users(user_id),
  FOREIGN KEY (movie_id) REFERENCES Movies(movie_id)
); 

I noticed when reading about foreign keys there is an 'ON DELETE' and 'ON UPDATE' option where you can set to restrict, cascade etc... 我注意到在阅读有关外键时有一个'ON DELETE'和'ON UPDATE'选项,您可以在其中设置限制,级联等。

If a user has favourited many movies, and then one of the movies is deleted from the movie table, what would happen if it the foreign key was set to "CASCADE"? 如果用户收藏了许多电影,然后从电影表中删除了其中一部电影,如果将外键设置为“ CASCADE”会发生什么情况? would any rows from the favourites table be deleted also? 收藏夹表中的任何行也会被删除吗? What would happen if the foreign key was set to "RESTRICT"? 如果外键设置为“ RESTRICT”,将会发生什么?

I am just after a basic explanation as I do not currently fully understand this. 我只是进行基本的解释,因为我目前尚不完全了解。

13.1.17.3 Using FOREIGN KEY Constraints 13.1.17.3使用外键约束

... ...

  • CASCADE : Delete or update the row from the parent table, and automatically delete or update the matching rows in the child table. CASCADE :从父表中删除或更新行,并自动删除或更新子表中匹配的行。 Both ON DELETE CASCADE and ON UPDATE CASCADE are supported. 同时支持ON DELETE CASCADEON UPDATE CASCADE Between two tables, do not define several ON UPDATE CASCADE clauses that act on the same column in the parent table or in the child table. 在两个表之间,不要定义作用于父表或子表中同一列上的几个ON UPDATE CASCADE子句。

    Note 注意

    Currently, cascaded foreign key actions do not activate triggers. 当前,级联的外键操作无法激活触发器。

... ...

  • RESTRICT : Rejects the delete or update operation for the parent table. RESTRICT :拒绝父表的删除或更新操作。 Specifying RESTRICT (or NO ACTION ) is the same as omitting the ON DELETE or ON UPDATE clause. 指定RESTRICT (或NO ACTION )与省略ON DELETEON UPDATE子句相同。

  • NO ACTION : A keyword from standard SQL. NO ACTION :来自标准SQL的关键字。 In MySQL, equivalent to RESTRICT . 在MySQL中,等效于RESTRICT The MySQL Server rejects the delete or update operation for the parent table if there is a related foreign key value in the referenced table. 如果引用表中有相关​​的外键值,则MySQL服务器会拒绝父表的删除或更新操作。 Some database systems have deferred checks, and NO ACTION is a deferred check. 某些数据库系统具有延迟检查,而“ NO ACTION”是延迟检查。 In MySQL, foreign key constraints are checked immediately, so NO ACTION is the same as RESTRICT . 在MySQL中,立即检查外键约束,因此NO ACTIONRESTRICT相同。

... ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM