MySQL错误1005:外键约束形成错误

时间:2018-06-13 11:35:13

标签: mysql sql database

我使用MySQL处理数据库,我有一个主日历表日期,它与另一个 astreinte_mensu 共享一些列(年和月),我'我成功创造了一些PRIMARY KEYS但是当我来制作FOREIGN KEYS时我得到了以下错误:

ERROR 1005 (HY000) at line 33: Can't create table `testDB`.`astreinte_mensu`
(errno: 150 "Foreign key constraint is incorrectly formed")

详细错误输出:

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.

日期表:

CREATE TABLE date(
   dateID int NOT NULL,
   annee int NOT NULL,
   mois int NOT NULL,
   semaine int NOT NULL,
   jour int NOT NULL,
   CONSTRAINT PK_date PRIMARY KEY (dateID,annee,mois,semaine,jour)
) Engine=innoDB;

Astreinte_mensu表:

CREATE TABLE astreinte_mensu(
   annee int,
   mois int,
   Personne1Nuit int,
   Personne2Nuit int,
   Personne1Jour int,
   Personne2Jour int,
   FOREIGN KEY (annee) REFERENCES date(annee),
   FOREIGN KEY (mois) REFERENCES date(mois),
   FOREIGN KEY (Personne1Nuit) REFERENCES contact(PersonID),
   FOREIGN KEY (Personne2Nuit) REFERENCES contact(PersonID),
   FOREIGN KEY (Personne1Jour) REFERENCES contact(PersonID),
   FOREIGN KEY (Personne2Jour) REFERENCES contact(PersonID)
) Engine=innoDB;

我已经检查过日期表是在另一个之前创建的 并且列来自相同的数据类型。

有没有人知道可能出错的地方?

提前致谢

1 个答案:

答案 0 :(得分:0)

MySQL中的外键必须引用另一个具有索引的表中的列,理想情况下是唯一索引。这通常发生在其他列是主键时,但只要有索引它也不能是主键。在当前代码中,您从五列中创建了一个主键:

CONSTRAINT PK_date PRIMARY KEY (dateID, annee, mois, semaine, jour)

但所有这些意味着这五个值在一起的每个组合必须是唯一的。这并不意味着任何一列都有索引。

我在您的代码中看到的直接问题是您指的是annee表中的moisastreinte_mensu。我们可以尝试为这些列添加唯一约束。以下是可能有效的代码版本:

CREATE TABLE date (
    dateID int NOT NULL,
    annee int NOT NULL,
    mois int NOT NULL,
    semaine int NOT NULL,
    jour int NOT NULL,
    CONSTRAINT PK_date PRIMARY KEY (dateID, annee, mois, semaine, jour),
    UNIQUE KEY idx_annee (annee),
    UNIQUE KEY idx_mois (mois)
) Engine=innoDB;

CREATE TABLE astreinte_mensu (
    annee int,
    mois int,
    Personne1Nuit int,
    Personne2Nuit int,
    Personne1Jour int,
    Personne2Jour int,
    FOREIGN KEY (annee) REFERENCES date(annee),
    FOREIGN KEY (mois) REFERENCES date(mois),
    FOREIGN KEY (Personne1Nuit) REFERENCES contact(PersonID),
    FOREIGN KEY (Personne2Nuit) REFERENCES contact(PersonID),
    FOREIGN KEY (Personne1Jour) REFERENCES contact(PersonID),
    FOREIGN KEY (Personne2Jour) REFERENCES contact(PersonID)
 ) Engine=innoDB;

我假设contact表的列PersonID是唯一的。如果没有,这将是另一个错误原因。