MySql 外键约束,错误 1005

标签 mysql sql foreign-keys innodb foreign-key-relationship

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

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

最佳答案

尝试

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

将外键从articles添加到newsgroups

关于MySql 外键约束,错误 1005,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11698803/

相关文章:

mysql - 正确使用 mysql 中的 WHERE NOT

mysql - 获取受帖子类别限制的自定义字段值列表

c# - Entity Framework 代码优先外键问题

mysql - 如何获取MySQL每秒的状态变量?

php - 动态表单并循环表单数组插入Mysql

mysql - SQL:输出属于某个类别的所有名称,其中该类别中的所有国家/地区都相同

sql - Oracle 全局临时表 - 最大记录数?

c# - 表格未显示在 Visual Studio 2012 中

mysql - 无法在 MySQL 中创建外键约束

php - 使 Yii Dropdown 默认值为 NULL