同一个表的 MySQL 外键失败,错误 1005,errno 150
mysql> ALTER TABLE category ADD CONSTRAINT category_parent_category_id FOREIGN KEY (parent) REFERENCES category(id);
ERROR 1005 (HY000): Can't create table 'sfnews.#sql-244_1' (errno: 150)
DDL如下:
Create Table: CREATE TABLE `category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`parent` bigint(20) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `parent_idx` (`parent`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
为什么会出错?
mysql> ALTER TABLE category ADD CONSTRAINT category_parent_category_id FOREIGN KEY (parent) REFERENCES category(id);
ERROR 1005 (HY000): Can't create table 'sfnews.#sql-244_1' (errno: 150)
DDL as follows:
Create Table: CREATE TABLE `category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`parent` bigint(20) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `parent_idx` (`parent`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Why is it wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
自参考应该是可能的。这是因为“parent”是无符号的,而“id”则不是。将表定义 id 列更改为
,它将起作用。
参考说明了有关外键的信息: “整数类型的大小和符号必须相同”
似乎与描述的问题相同此处
Self reference should be possible. It's because "parent" is unsigned and "id" is not. Change the table definitions id column to
and it will work.
The reference states about foreign keys: "The size and sign of integer types must be the same"
Seems to be the same problem described here
如果您检查 InnoDB 引擎的状态(
SHOW ENGINE InnoDB STATUS
),您将得到更完整的解释:使
id
无符号。If you check the status of the InnoDB engine (
SHOW ENGINE InnoDB STATUS
), you'll get a fuller explanation:Make
id
unsigned.