假设我有两个表:students
和 course_scores
。
students
中的属性为student_id、name、sex
;
而course_scores
中的属性为student_id、course、score
。
当我删除students
中的记录时,course_scores
中相应的记录也应该被删除,对吧?使它们保持一致。
你能告诉我执行此操作的代码吗?
最佳答案
ALTER TABLE course_scores ADD FOREIGN KEY (student_id) REFERENCES
students (student_id) ON DELETE CASCADE
ON DELETE CASCADE
部分就是您想要的;如果相应的 student_id
被删除,这将删除 course_scores
中的所有行。您的表必须使用 InnoDB
引擎。
关于mysql - 如何在删除其中一个表的记录时保持两个表的数据一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14926156/