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