gpt4 book ai didi

mysql - 外键失败

转载 作者:行者123 更新时间:2023-11-29 03:10:10 25 4
gpt4 key购买 nike

好的,所以我一直在努力弄清楚为什么我总是收到这个特定的错误。 MySql 一直给我错误代码 1452。无法添加或更新子行。我的 table 就是这样。

CREATE  TABLE IF NOT EXISTS `ecommerce`.`departments` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(100) NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = MyISAM;

INSERT INTO `ecommerce`.`departments`
VALUES (1, 'Development'), (2, 'Marketing'),
(3, 'Sales'), (4, 'Customer Service');

CREATE TABLE IF NOT EXISTS `ecommerce`.`department_roles` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(100) NOT NULL ,
`map` VARCHAR(255) NOT NULL ,
`parent_id` INT NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = MyISAM;

INSERT INTO `ecommerce`.`department_roles`
VALUES (1, 'Admin', '/admin', 0), (2, 'Create', '/admin', 1),
(3, 'Update', '/admin', 1), (4, 'Delete', '/admin', 1);

CREATE TABLE IF NOT EXISTS `ecommerce`.`department_roles_map` (
`id` INT NOT NULL AUTO_INCREMENT ,
`department_roles_id` INT NOT NULL ,
`departments_id` INT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_drm_departments` (`departments_id` ASC) ,
INDEX `fk_drm_department_roles` (`department_roles_id` ASC) ,
CONSTRAINT `fk_drm_departments`
FOREIGN KEY (`departments_id` )
REFERENCES `ecommerce`.`departments` (`id` )
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_drm_department_roles`
FOREIGN KEY (`department_roles_id` )
REFERENCES `ecommerce`.`department_roles` (`id` )
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;

现在,当我尝试从 departments 和 department_roles 中进行选择时,我会显示数据。

SELECT * FROM department_roles;
+----+--------+--------+-----------+
| id | name | map | parent_id |
+----+--------+--------+-----------+
| 1 | Admin | /admin | 0 |
| 2 | Create | /admin | 1 |
| 3 | Update | /admin | 1 |
| 4 | Delete | /admin | 1 |
+----+--------+--------+-----------+
4 rows in set (0.00 sec)

SELECT * FROM departments;
+----+--------+--------+-----------+
| id | name | map | parent_id |
+----+--------+--------+-----------+
| 1 | Admin | /admin | 0 |
| 2 | Create | /admin | 1 |
| 3 | Update | /admin | 1 |
| 4 | Delete | /admin | 1 |
+----+--------+--------+-----------+
4 rows in set (0.00 sec)

但是,当我尝试插入 department_roles_map 时,我明白了。

INSERT INTO department_roles_map(department_roles_id, departments_id) VALUES (1, 1);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`ecommerce`.`department_roles_map`, CONSTRAINT `fk_drm_departments` FOREIGN KEY (`departments_id`) REFERENCES `departments` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION)

如有任何帮助,我们将不胜感激!

最佳答案

首先,令我印象深刻的是您设法创建了一个 InnoDB 表,该表具有对两个 MyISAM 表的 FK 引用!

尝试使用 InnoDB 引擎创建所有三个表并重试....

关于mysql - 外键失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9790240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com