2011-04-29 4 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을 게시 할 수 있습니까? –

+0

그냥 오타입니까, 아니면 실제로'tags'와'tag' 테이블이 있습니까? 제약 조건 오류는'tag'라는 테이블을 참조하지만 쿼리는'tags'와 반대입니다. – Thomas

+0

위와 마찬가지로 테이블의 이름은'tags'이지만'References' 제약 조건은'tag'라는 테이블을 가리 킵니다. – Thomas

답변

2

, 그것은 나타납니다 그 외부 키 post_tag_map.tag_id에있는 열은 tags 테이블과 대조적으로 tag 테이블을 가리 킵니다.

+1

** 홍당무 *** :( – Pardoner