[英]MySQL foreign key to the same table failed with error 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 as follows: 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
Why is it wrong? 为什么这是错的?
Self reference should be possible. 应该可以自我参考。 It's because "parent" is unsigned and "id" is not.
这是因为“父”是无符号的而“id”不是。 Change the table definitions id column to
将表定义id列更改为
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
and it will work. 它会起作用。
The reference states about foreign keys: "The size and sign of integer types must be the same" 关于外键的引用说明:“整数类型的大小和符号必须相同”
If you check the status of the InnoDB engine ( SHOW ENGINE InnoDB STATUS
), you'll get a fuller explanation: 如果您检查InnoDB引擎的状态(
SHOW ENGINE InnoDB STATUS
),您将获得更全面的解释:
LATEST FOREIGN KEY ERROR
最新的外国关键错误
[...]
[...]
Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint.
在引用的表中找不到索引,其中引用的列显示为第一列,或者表中的列类型与引用的表不匹配约束。
Make id
unsigned. 使
id
无符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.