我收到一条错误消息:Error Code: 1217. Cannot delete or update a parent row: a foreign key constraint fails
不确定我为什么会收到此错误。任何线索?
以下代码:
-- DROP EXISTING TABLES --
DROP TABLE IF EXISTS `category`;
DROP TABLE IF EXISTS `format`;
DROP TABLE IF EXISTS `customer`;
DROP TABLE IF EXISTS `rentals`;
DROP TABLE IF EXISTS `videos`;
-- CREATE CATEGORY TABLE --
CREATE TABLE `category` (
`category_id` int(10) NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;
-- CREATE FORMAT TABLE --
CREATE TABLE `format` (
`format_id` int(10) NOT NULL,
PRIMARY KEY (`format_id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;
-- CRTEATE VIDEOS TABLE --
CREATE TABLE `videos` (
`video_id` int(10) NOT NULL,
`title` varchar(50) NOT NULL,
`format_id` int(10) NOT NULL,
`cost` double NOT NULL,
`category_id` int(10) NOT NULL,
PRIMARY KEY (`video_id`),
CONSTRAINT `fk_video_format` FOREIGN KEY (`format_id`) REFERENCES `format` (`format_id`),
CONSTRAINT `fk_video_category` FOREIGN KEY (`category_id`) REFERENCES `category` (`category_id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;
-- CREATE CUSTOMER TABLE --
CREATE TABLE `customer` (
`customer_id` int(10) NOT NULL,
`last_name` varchar(50) NOT NULL,
`first_name` varchar(50) NOT NULL,
`address` varchar(100) NOT NULL,
`city` varchar(50) NOT NULL,
`state` varchar(10) NOT NULL,
`zip` int(10) NOT NULL,
PRIMARY KEY (`customer_id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;
-- CREATE RENTALS TABLE --
CREATE TABLE `rentals` (
`rental_id` int(10) NOT NULL,
`date_out` datetime NOT NULL,
`date_due` datetime NOT NULL,
`date_in` datetime NOT NULL,
`delivery_status` varchar(50),
`cost` double NOT NULL,
`late_fee` double NOT NULL,
`customer_id` int(10) NOT NULL,
`video_id` int(10) NOT NULL,
PRIMARY KEY (`rental_id`),
CONSTRAINT `fk_video_customer` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`customer_id`),
CONSTRAINT `fk_video_cost` FOREIGN KEY (`cost`) REFERENCES `videos` (`cost`),
CONSTRAINT `fk_video_id` FOREIGN KEY (`video_id`) REFERENCES `videos` (`video_id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;
我相信一切都与关键和外键关键。格式化看起来也是正确的。除非我在这里做了一些完全错误的事情。
答案 0 :(得分:0)
忽略上面评论中描述的cost
问题,1217
错误很常见,因为当您放弃时,您必须按照创建的保留顺序执行此操作才能安全地执行此操作。
假设您已成功连续创建表A,B,C,D,您需要按照D,C,B,A的顺序删除它们。
这只是因为如果孩子有FK有效,就不能删除父母。通过首先放弃孩子,错误不会浮出水面。