首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MySql外键约束,错误1005

MySql外键约束,错误1005
EN

Stack Overflow用户
提问于 2012-07-28 14:18:58
回答 1查看 1.3K关注 0票数 2

我可以see说有约束问题,但是在这里创建外键的正确方法是什么呢?

代码语言:javascript
复制
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查询浏览器生成:

代码语言:javascript
复制
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;

这将导致相同的错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-28 14:26:14

试一试

代码语言:javascript
复制
ALTER TABLE articles
ADD FOREIGN KEY
newsgroup_fk (newsgroup_id)
REFERENCES newsgroups (id)

若要向newsgroups添加来自articles的外键,请执行以下操作。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11698803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档