MySQL Error 1452 - Cannot add or update a child row: a foreign key constraint fails
Posted
by dscher
on Stack Overflow
See other posts from Stack Overflow
or by dscher
Published on 2010-04-24T04:46:23Z
Indexed on
2010/04/24
4:53 UTC
Read the original article
Hit count: 754
I've looked at other people's questions on this topic but can't seem to find where my error is coming from. Any help would be greatly appreciated. I'm including as much as I can think of that might help find the problem:
CREATE TABLE stocks (
id INT AUTO_INCREMENT NOT NULL,
user_id INT(11) UNSIGNED NOT NULL,
ticker VARCHAR(20) NOT NULL,
name VARCHAR(20),
rating INT(11),
position ENUM("strong buy", "buy", "sell", "strong sell", "neutral"),
next_look DATE,
privacy ENUM("public", "private"),
PRIMARY KEY(id),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `stocks_tags` (
`stock_id` INT NOT NULL,
`tag_id` INT NOT NULL,
PRIMARY KEY (`stock_id`,`tag_id`),
KEY `fk_stock_tag` (`tag_id`),
KEY `fk_tag_stock` (`stock_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `stocks_tags`
ADD CONSTRAINT `fk_stock_tag` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_tag_stock` FOREIGN KEY (`stock_id`) REFERENCES `stocks` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
CREATE TABLE tags(
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
tags VARCHAR(30),
UNIQUE(tags)
)
ENGINE=INNODB DEFAULT CHARSET=utf8;
And the error I'm getting:
Database_Exception [ 1452 ]: Cannot add or update a child row: a foreign key constraint
fails (`ddmachine`.`stocks_tags`, CONSTRAINT `fk_stock_tag` FOREIGN KEY (`tag_id`) REFERENCES
`tags` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) [ INSERT INTO `stocks_tags` (`stock_id`,
`tag_id`) VALUES (19, 'cash') ]
I did see that someone else had a similar problem based on their enum columns but don't think that's it.
© Stack Overflow or respective owner