问题描述
我原以为 ON UPDATE CASCADE
约束可以让我更新引用外键的值,并将其级联到它的裁判(就像在 Postgresql 中那样),但情况似乎并非如此。
我错过了什么吗?
此处使用 MariaDB 10.3.29-MariaDB-0ubuntu0.20.04.1
CREATE TABLE category (
id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,parent_id int(11) UNSIGNED DEFAULT NULL,slug varchar(255) NOT NULL,title varchar(255) NOT NULL,content longtext NOT NULL,created_at datetime NOT NULL DEFAULT current_timestamp(),updated_at datetime DEFAULT NULL,CONSTRAINT fk_category_parent_id FOREIGN KEY (parent_id) REFERENCES category (id) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `category` (`id`,`parent_id`,`slug`,`title`,`content`,`created_at`,`updated_at`) VALUES
(1,NULL,'non-classe','Non Classé','','2021-05-30 16:46:52',NULL),(2,'cours','Cours','2021-05-30 16:47:38',(3,2,'MysqL','MysqL','2021-05-30 16:48:18',(4,3,'initiation-MysqL','Cours initiation MysqL','2021-05-30 16:49:09',NULL);
UPDATE category SET id = 12 WHERE id = 2;
-- ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`cours_cms`.`category`,CONSTRAINT `fk_category_parent_id` FOREIGN KEY (`parent_id`) REFERENCES `category` (`id`) ON UPDATE CASCADE)
解决方法
查看本页评论:
https://mariadb.com/kb/en/foreign-keys/
如果 ON UPDATE CASCADE 递归更新它之前在级联期间更新的同一个表,它的作用类似于 RESTRICT。这意味着您不能使用自引用 ON UPDATE CASCADE 操作。这是为了防止级联更新导致无限循环。
换句话说,如果它是一种分层数据类型的表,则 ON UPDATE CASCADE 不起作用。
,只是确认这在没有“无限循环”的情况下在 PostgreSQL 中有效
CREATE TABLE category (
id SERIAL PRIMARY KEY,parent_id int DEFAULT NULL,slug varchar(255) NOT NULL,title varchar(255) NOT NULL,content text NOT NULL,CONSTRAINT fk_category_parent_id FOREIGN KEY (parent_id) REFERENCES category (id) ON DELETE RESTRICT ON UPDATE CASCADE
);
INSERT INTO category (id,parent_id,slug,title,content) VALUES
(1,NULL,'non-classe','Non Classé',''),(2,'cours','Cours',(3,2,'mysql','MySQL',(4,3,'initiation-mysql','Cours initiation MySQL','');
UPDATE category SET id=12 WHERE id=2;
SELECT * FROM category;
id | parent_id | slug | title | content
----+-----------+------------------+------------------------+---------
1 | | non-classe | Non Classé |
4 | 3 | initiation-mysql | Cours initiation MySQL |
12 | | cours | Cours |
3 | 12 | mysql | MySQL |