Reputation: 41
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.
Upvotes: 1
Views: 2295
Reputation: 6534
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!
Upvotes: 0
Reputation: 1812
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())
Upvotes: 1
Reputation: 312219
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 ---^
Upvotes: 2