简体   繁体   English

将带有FOREIGN KEY的表添加到MySQL数据库会导致errno 150

[英]Adding table with FOREIGN KEY to a MySQL database causes errno 150

I'm attemping to execute the following SQL and am receiving errno: 150 'cannot create table path_relations' in response. 我正在尝试执行以下SQL并收到errno:150'无法创建表path_relations'作为响应。 According to the MySQL documentation this is caused by my FOREIGN KEY restraints having issues. 根据MySQL文档,这是由我的FOREIGN KEY约束引起的。 What am I doing wrong? 我究竟做错了什么?

DROP TABLE IF EXISTS `paths`;
DROP TABLE IF EXISTS `path_relations`;

CREATE TABLE `paths` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(256) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `path_relations` (
    `ancestor` int(11) NOT NULL DEFAULT '0',
    `descendant` int(11) NOT NULL DEFAULT '0',
    PRIMARY KEY(`ancestor`, `descendant`),
    FOREIGN KEY(`ancestor`) REFERENCES paths(`id`),
    FOREIGN KEY(`descendant`) REFERENCES paths(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Here is a checklist for you, good luck ;) 这是您的清单,祝您好运;)

1) type of foreign key source and reference fields must be identical 1)外键源的类型和参考字段必须相同

2) both source and reference fields must be unsigned 2)源域和引用域都必须未签名

3) source field must be indexed 3)源字段必须被索引

4) both tables must be InnoDB 4)两个表都必须是InnoDB

如果您将paths.id 签名,是否paths.id

UPDATED: In the first table you define your integer value as unsigned whilst in the second you haven't. 更新:在第一个表中,您将整数值定义为无符号,而在第二个表中,您没有定义。 The fields must be identical in structure to satisfy a foreign key. 这些字段的结构必须相同才能满足外键。

Do you have any data in the table already? 表格中是否已有数据? if so make sure that all records would satisfy the constraint. 如果是这样,请确保所有记录都将满足约束条件。 NULL values in the foreign keyed column will prevent this from working. 外键列中的NULL值将阻止此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM