1
这怎么可能:MySQL的外键约束失败
mysql> select id from posts;
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)
mysql> select id from tags;
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)
mysql> insert into pots_x_tags values(1,1);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`posts_x_tags`, CONSTRAINT `posts_x_tags_ibfk_2` FOREIGN KEY (`tag_id`) REFERENCES `tag` (`id`) ON DELETE CASCADE)
下面是表(很多到很多):
CREATE TABLE `post_tag_map` (
`post_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL,
PRIMARY KEY (`post_id`,`tag_id`),
FOREIGN KEY (`post_id`) REFERENCES posts(`id`) ON DELETE CASCADE,
FOREIGN KEY (`tag_id`) REFERENCES tag(`id`) ON DELETE CASCADE
)
CREATE TABLE `tags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tag` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE (`tag`)
)
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) CHARACTER SET latin1 NOT NULL,
`body` text CHARACTER SET latin1,
PRIMARY KEY (`id`)
)
你可以发布用于创建两个表的MySQL吗? – 2011-04-29 18:36:49
它只是一个错字,或者实际上是一个'tags'和'tag'表吗?约束错误引用了一个名为'tag'的表,但是您的查询是针对'tags'的。 – Thomas 2011-04-29 18:49:21
与上面类似,该表被命名为'tags',但是'References'约束指向一个名为'tag'的表。 – Thomas 2011-04-29 18:58:23