2012-07-28 90 views
2

我可以see有约束问题,但是在这里创建一个外键的正确方法是什么?MySql FOREIGN KEY约束,错误1005

mysql> 
mysql> show tables; 
+----------------+ 
| Tables_in_nntp | 
+----------------+ 
| articles  | 
| newsgroups  | 
+----------------+ 
2 rows in set (0.01 sec) 

mysql> 
mysql> describe newsgroups; 
+-----------+---------+------+-----+---------+----------------+ 
| Field  | Type | Null | Key | Default | Extra   | 
+-----------+---------+------+-----+---------+----------------+ 
| id  | int(11) | NO | PRI | NULL | auto_increment | 
| newsgroup | text | NO |  | NULL |    | 
+-----------+---------+------+-----+---------+----------------+ 
2 rows in set (0.00 sec) 

mysql> 
mysql> describe articles; 
+--------------+---------+------+-----+---------+----------------+ 
| Field  | Type | Null | Key | Default | Extra   | 
+--------------+---------+------+-----+---------+----------------+ 
| id   | int(11) | NO | PRI | NULL | auto_increment | 
| subject  | text | NO |  | NULL |    | 
| content  | text | NO |  | NULL |    | 
| number  | text | NO |  | NULL |    | 
| sent   | date | NO |  | NULL |    | 
| header_id | text | NO |  | NULL |    | 
| newsgroup_id | int(11) | NO |  | NULL |    | 
+--------------+---------+------+-----+---------+----------------+ 
7 rows in set (0.00 sec) 

mysql> 
mysql> ALTER TABLE articles ADD FOREIGN KEY (newsgroup_id) REFERENCES newsgroup(id); 
ERROR 1005 (HY000): Can't create table 'nntp.#sql-3bf_9a' (errno: 150) 
mysql> 

两张表都使用innodb。

MySQL查询浏览器生成:

ALTER TABLE `nntp`.`articles` ADD CONSTRAINT `new_fk_constraint` FOREIGN KEY `new_fk_constraint` (`newsgroup_id`) 
    REFERENCES `newsgroups` (`id`) 
    ON DELETE SET NULL 
    ON UPDATE SET NULL; 

其导致相同的错误。

enter image description here

回答

2

尝试

ALTER TABLE articles 
ADD FOREIGN KEY 
newsgroup_fk (newsgroup_id) 
REFERENCES newsgroups (id) 

一个外键添加从articlesnewsgroups

+0

谢谢。后续问题:为什么GUI生成代码(请参阅更新后的问题)不起作用?它给出相同的错误编号。 – Thufir 2012-07-28 06:33:52

+1

我认为这是因为'on ... set NULL'。你的'newsgroup_id'被定义为'not null'。如果外键在'newsgroups'表中被删除,它会将它设置为'null'。碰撞。你可以用'cascade'替换'set null'来删除新闻组被删除的文章。或者使用“无动作”不做任何事情。它是由你决定。 – 2012-07-28 06:42:51