这怎么可能:
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`)
)
答案 0 :(得分:2)
从表面上看,post_tag_map.tag_id
列上的外键似乎指向名为tag
的表,而不是名为tags
的表。