简体   繁体   中英

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.

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' ).

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. I added tables and relationships (FK) and things went KaBoom!

Upon investigation, I found the other buddy was using MyIsam Engine for that table and I was using InnoDB.

Changing the table from MyIsam to InnoDB ssolved the Issue!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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