当我尝试从评估表中删除记录时,我收到此错误。
Cannot delete or update a parent row: a foreign key constraint fails (`assessment`.`assessment_answer`, CONSTRAINT `consAssessmentId` FOREIGN KEY (`assessment_id`) REFERENCES `assessment` (`id`)). The SQL statement executed was: DELETE FROM `assessment` WHERE created_by=14
我必须删除用户的所有数据,包括这些表中的记录:用户,评估,评估答案。
我可以轻松删除用户记录但删除评估表记录时出现上述错误。在评估表之后,我还需要从评估答案表中删除用户记录。
你可以帮我解决这个问题吗?
我有3个表:评估答案
CREATE TABLE IF NOT EXISTS `assessment_answer` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`assessment_id` int(10) DEFAULT NULL,
`create_date` datetime DEFAULT NULL,
`question_id` int(10) DEFAULT NULL,
`answer_value` int(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `question_id` (`question_id`),
KEY `assessment_id` (`assessment_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=200 ;
评估表:
CREATE TABLE IF NOT EXISTS `assessment` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`link` varchar(255) DEFAULT NULL,
`created_by` int(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `created_by_2` (`created_by`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
和用户表:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`email` varchar(255) DEFAULT NULL,
`status` enum('0','1','2') NOT NULL DEFAULT '1' COMMENT '0: Inactive, 1: Active, 2: Deleted',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
如果我接受SQL转储,我会得到这个,
--
-- Constraints for table `assessment_answer`
--
ALTER TABLE `assessment_answer`
ADD CONSTRAINT `consAssessmentId` FOREIGN KEY (`assessment_id`) REFERENCES `assessment` (`id`),
ADD CONSTRAINT `consQuestionId` FOREIGN KEY (`question_id`) REFERENCES `questions` (`id`);
答案 0 :(得分:0)
此处assessment
为父级,assessment_answer
为子级。 1父母可能有很多孩子。 1个孩子只有1个父母。
假设您可以成功从assessment
表中删除记录ID 100,那么assessment_answer
表中assessment_id
为100的所有记录将变为无效(评估记录ID 100已经消失) !)。数据完整性被打破。
有两种解决方案:
1)手动,必须先删除assessment_answer
条记录,然后才能删除assessment
条记录。换句话说,首先删除与父项关联的子记录,然后删除父项。
DELETE FROM assessment_answer WHERE assessment_id = 100
DELETE FROM assessment WHERE id = 100
2)从技术上讲,你可以让Mysql通过在父子关系的外部约束上声明ON DELETE CASCADE
来处理任务
ALTER TABLE `assessment_answer`
ADD CONSTRAINT `consAssessmentId` FOREIGN KEY (`assessment_id`) REFERENCES `assessment` (`id`) ON DELETE CASCADE
当父数据被删除时,它告诉Mysql 始终删除子数据。然后,只执行一个SQL命令以删除两个表中的相关记录
DELETE FROM assessment WHERE created_by = 14