简体   繁体   English

无法添加或更新子行:外键约束失败(mysql中的外键问题)

[英]Cannot add or update a child row: a foreign key constraint fails(Foreign key issue in mysql)

I am getting this error whenever I try to Insert Data into my "Student" table. 每当我尝试将数据插入“学生”表时,都会出现此错误。 Below are the two tables, I am using MySql : 下面是两个表,我正在使用MySql:

student table: 学生桌:

| Field        | Type         | Null | Key | Default           | Extra          |
+--------------+--------------+------+-----+-------------------+----------------+
| S_id         | int(20)      | NO   | PRI | NULL              | auto_increment |
| U_id         | int(11)      | YES  | MUL | NULL              |                |
| sname        | varchar(20)  | YES  |     | NULL              |                |
| gender       | varchar(20)  | YES  |     | NULL              |                |
| email        | varchar(320) | YES  | UNI | NULL              |                |
| Phone_Number | int(20)      | YES  |     | NULL              |                |

user table: 用户表:

Field    | Type         | Null | Key | Default           | Extra          |
+----------+--------------+------+-----+-------------------+----------------+
| U_id     | int(11)      | NO   | PRI | NULL              | auto_increment |
| name     | varchar(100) | NO   |     | NULL              |                |
| password | varchar(20)  | NO   |     | NULL              |                |
| email    | varchar(255) | NO   | UNI | NULL              |                |

When I try to run this query , 当我尝试运行此查询时,

INSERT INTO student(U_id,sname,gender,email,Phone_Number) VALUES ('$U_id','$sname','$gender','$email','$Phone_Number');

I am getting this error: 我收到此错误:

Cannot add or update a child row: a foreign key constraint fails (`Learn`.`student`, CONSTRAINT `student_ibfk_1` FOREIGN KEY (`U_id`) REFERENCES `user` (`U_id`))

I tried to look for the solution but most of them are saying keep a common Engine like InnoDB on both the tables but in my table its already defined.I have even followed the steps given here https://stackoverflow.com/a/9139206/2545197 but nothing worked for me. 我试图寻找解决方案,但大多数人都说要在两个表上都保留一个像InnoDB这样的通用引擎,但是在我的表中已经定义了它。我什至遵循了此处给出的步骤https://stackoverflow.com/a/9139206 / 2545197,但对我没有任何帮助。

I made an SQL Fiddle and everything works perferctly. 我做了一个SQL Fiddle ,一切正常。

The only way I can reproduce the error is when a row is inserted into student before the corresponding row in user exists. 我可以重现该错误的唯一方法是在用户中相应行存在之前将一行插入到student中。 Can you please double check that this is really true for each inserted row. 能否请您再次检查每个插入行是否确实如此。

Also, you should var_dump() your PHP variables used for the INSERT and check if the problem lies there. 另外,您应该将var_dump()用于INSERT PHP变量检查是否存在问题。 IMHO, it can only have to do with a non-existing record in the user table . 恕我直言,它只能与user 表中 不存在的记录有关

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM