[英]Mysql: Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails
I have this table: 我有这张桌子:
CREATE TABLE comments(
comment_id int(11) NOT NULL auto_increment,
user_id int(11) NOT NULL,
product_id int(11) NOT NULL,
comment_text varchar(1000) COLLATE utf8_czech_ci NOT NULL,
uploaded datetime NOT NULL,
primary key(comment_id),
constraint fk_user_comments foreign key(user_id) references user(user_id) ON UPDATE CASCADE ON DELETE CASCADE,
constraint fk_product_comments foreign key(product_id) references product(product_id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci;
and I'm trying to insert data into this table. 并且我正在尝试将数据插入此表中。
INSERT INTO comments(user_id,product_id,comment_text,uploaded) VALUES(1,'brbr',1,Now());
But for some reason I keep getting this error: 但是由于某种原因,我不断收到此错误:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`project`.`comments`, CONSTRAINT `fk_product_comments` FOREIGN KEY (`product_id`) REFERENCES `product` (`product_id`) ON DELETE CASCADE ON UPDATE CASCADE)
User with id 1 exists and product with id 1 exists so now i have no idea whats causing the problem. 用户ID为1,产品ID为1,所以现在我不知道是什么引起了问题。
You've got your column list's order messed up. 您已经弄乱了列列表的顺序。 You're attempting to insert a row with a
product_id
of 'brbr'
(which MySQL treats as 0) and a comment text of 1
(which MySQL converts as to '1'
). 您正在尝试插入
product_id
为'brbr'
(MySQL视为0)和注释文本为1
(MySQL转换为'1'
)的行。
Reordering the the column list to match the values (or vise-versa) should solve it: 重新排序列列表以匹配值(反之亦然)应该可以解决它:
INSERT INTO comments
(user_id, product_id, comment_text, uploaded)
VALUES (1, 1, 'brbr', NOW());
-- Here ---^
This because you are not adding value according to your column sequence. 这是因为您没有根据列顺序增加价值。
This is correct query. 这是正确的查询。
INSERT INTO comments(user_id,product_id,comment_text,uploaded) VALUES(1,1,'brbr',Now())
I met the same problem today as I was dealing with Schema that wasn't designed by me. 今天,当我处理不是由我设计的Schema时遇到了相同的问题。 I added tables and relationships (FK) and things went KaBoom!
我添加了表和关系(FK),事情就发生了!
Upon investigation, I found the other buddy was using MyIsam Engine for that table and I was using InnoDB. 经过调查,我发现另一个伙伴正在对该表使用MyIsam Engine,而我正在使用InnoDB。
Changing the table from MyIsam to InnoDB ssolved the Issue! 将表从MyIsam更改为InnoDB解决了该问题!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.