0

任何人都可以判断子表中的外键是否可以自动获取它在父表中实际具有的值?我有两个表学生和课程表。学生 SSC 是课程中的外键。我将数据正确插入到学生表中。但是当我将数据插入课程表时它给了我一个错误?有什么建议吗?变量的值是通过表单的 post 方法获得的。

$query1=mysql_query("INSERT INTO course VALUES('','$subject','$total','$attendce','$ssn')")or die(mysql_error());

这是我得到的错误....

无法添加或更新子行:外键约束失败(`cast_db`.`course`, CONSTRAINT `course_ibfk_1` FOREIGN KEY (`cnic`) REFERENCES `student` (`cnic`) ON DELETE CASCADE ON UPDATE CASCADE)

4

1 回答 1

4

That's not how foreign keys work. You have to create a parent record first, get that record's ID (whatever the primary key happens to be) value, and then use that value in your child record insertions.

Remember - a parent table can have MANY records. There is no way for a database to know which of those records is the parent of a new child record. You HAVE to explicitly say that "this new child record has parent X".

于 2012-11-29T21:31:44.550 回答