令人困惑的是无法添加外键约束错误

时间:2015-04-18 04:54:37

标签: mysql

好吧,也许已经很晚了,我很蠢,但我似乎无法弄清楚为什么我为以下查询收到Cannot add Foreign Key Constraint错误

DROP TABLE IF EXISTS People_Lordships;
CREATE TABLE People_Lordships
(
    Id INT PRIMARY KEY AUTO_INCREMENT,
    PersonId INT NOT NULL,
    LordshipId INT NOT NULL,
    AssumedDate Date,
    AbdicatedDate Date
);

DROP TABLE IF EXISTS People_Lordships_Current;
CREATE TABLE People_Lordships_Current
(
    Id INT PRIMARY KEY AUTO_INCREMENT,
    People_LordshipsId INT NOT NULL,
    LordShipId INT NOT NULL,
    CONSTRAINT Fk_People_Lordships_Current_People_LordshipsId_LordshipId
    FOREIGN KEY (`LordshipId`,`People_LordshipsId`)
    REFERENCES People_Lordships (`LordshipId`,`Id`)
    ON DELETE RESTRICT ON UPDATE CASCADE,
    CONSTRAINT UQ_People_Lordships_Current_LordshipId
    UNIQUE KEY (`LordshipId`)
 );

是的,这是一个关于贵族头衔的数据库......这是一个很长的故事

2 个答案:

答案 0 :(得分:2)

LordshipId中没有列People_Lordships

您的外键定义试图引用一个不存在的列。

 REFERENCES People_Lordships (`LordshipId`,`Id`)
                              ^^^^^^^^^^^^

答案 1 :(得分:0)

想出这个。

事实证明,MySQL无法为不是索引中第一列的列添加外键约束。

以下内容可行

DROP TABLE IF EXISTS People_Lordships;
CREATE TABLE People_Lordships
(
Id INT PRIMARY KEY AUTO_INCREMENT,
PersonId INT NOT NULL,
LordshipId INT NOT NULL,
AssumedDate Date,
AbdicatedDate Date,
INDEX Idx_LordshipId (LordshipId)
);

DROP TABLE IF EXISTS People_Lordships_Current;
CREATE TABLE People_Lordships_Current
(
Id INT PRIMARY KEY AUTO_INCREMENT,
People_LordshipsId INT NOT NULL,
LordShipId INT NOT NULL,
CONSTRAINT Fk_People_Lordships_Current_People_LordshipsId_LordshipId
FOREIGN KEY (`LordshipId`,`People_LordshipsId`)
REFERENCES People_Lordships (`LordshipId`,`Id`)
ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT UQ_People_Lordships_Current_LordshipId
UNIQUE KEY (`LordshipId`)
);