2011-04-29 275 views
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`) 
) 
+1

你可以發佈用於創建兩個表的MySQL嗎? – 2011-04-29 18:36:49

+0

它只是一個錯字,或者實際上是一個'tags'和'tag'表嗎?約束錯誤引用了一個名爲'tag'的表,但是您的查詢是針對'tags'的。 – Thomas 2011-04-29 18:49:21

+0

與上面類似,該表被命名爲'tags',但是'References'約束指向一個名爲'tag'的表。 – Thomas 2011-04-29 18:58:23

回答

2

從表面上看,這似乎表明外鍵在post_tag_map.tag_id列指向名爲tag的表,而不是名爲tags的表。

+1

**臉紅*** :( – Pardoner 2011-04-29 19:02:11