SQL错误1215(HY000)无法添加外键约束。

时间:2015-04-11 22:13:44

标签: mysql sql sql-server foreign-keys

我查看了有关此主题的其他问题,并且普遍的共识是检查我的数据类型一致性。我正在尝试创建具有SSN和ProjectID作为外键的表'review',引用Table Reviewer中的SSN和Table Project中的ProjectID

CREATE TABLE Reviews(

ProjectID VARCHAR(10) NOT NULL,

SSN INTEGER NOT NULL CHECK

    (SSN>100000000 AND SSN<999999999),

ReviewerRole VARCHAR(50) NOT NULL,

FOREIGN KEY(SSN)REFERENCES Reviewer(SSN),

FOREIGN KEY(ProjectID)REFERENCES Project(ProjectID),

PRIMARY KEY(SSN,ProjectID)
);

以下是“Project”和“Reviewer”的创建表语句

CREATE TABLE Reviewer(
SSN INTEGER NOT NULL CHECK (SSN>100000000 AND SSN<999999999),
Firstname VARCHAR(50) NOT NULL,
Lastname VARCHAR(50) NOT NULL
);
CREATE TABLE Project(
ProjectID VARCHAR(10) NOT NULL,
Title VARCHAR(50),
Archived DATE NOT NULL,
ProjectStatus VARCHAR(50) NOT NULL,
PRIMARY KEY(ProjectID)
);

Project and Reviewer创建没有问题。如果我删除SSN的FK声明并保留ProjectID的FK声明,我的创建评论查询是有效的,但不是相反。

错误的原因是什么?我需要添加另一个约束吗?

3 个答案:

答案 0 :(得分:2)

您忘记在Reviewer表中的SSN列中添加主键。以下查询在sqlfiddle中正确构建:

CREATE TABLE Reviewer(
SSN INTEGER NOT NULL CHECK (SSN>100000000 AND SSN<999999999),
Firstname VARCHAR(50) NOT NULL,
Lastname VARCHAR(50) NOT NULL,
  PRIMARY KEY(SSN)
);
CREATE TABLE Project(
ProjectID VARCHAR(10) NOT NULL,
Title VARCHAR(50),
Archived DATE NOT NULL,
ProjectStatus VARCHAR(50) NOT NULL,
PRIMARY KEY(ProjectID)
);
CREATE TABLE Reviews(

ProjectID VARCHAR(10) NOT NULL,

SSN INTEGER NOT NULL CHECK

    (SSN>100000000 AND SSN<999999999),

ReviewerRole VARCHAR(50) NOT NULL,

FOREIGN KEY(SSN)REFERENCES Reviewer(SSN),

FOREIGN KEY(ProjectID)REFERENCES Project(ProjectID),

PRIMARY KEY(SSN,ProjectID)
);

答案 1 :(得分:1)

外键只能引用另一个表中的主键列,您需要将SNN作为主键列。

CREATE TABLE Reviewer(
SSN INTEGER NOT NULL primary key CHECK (SSN>100000000 AND SSN<999999999),
Firstname VARCHAR(50) NOT NULL,
Lastname VARCHAR(50) NOT NULL
);

答案 2 :(得分:1)

referenced列的foreign key列,需要Primary key unique constraint,因此您的Reviewer表需要:

CREATE TABLE Reviewer(
SSN INTEGER PRIMARY KEY CHECK (SSN>100000000 AND SSN<999999999),
Firstname VARCHAR(50) NOT NULL,
Lastname VARCHAR(50) NOT NULL
);

CREATE TABLE Reviewer(
SSN INTEGER NOT NULL CHECK (SSN>100000000 AND SSN<999999999),
Firstname VARCHAR(50) NOT NULL,
Lastname VARCHAR(50) NOT NULL,
UNIQUE(SSN)
);

据我所知,MySQL忽略Check约束,因此您可以删除它们。