MySQL错误1215-外键(日期类型)到主键(日期类型)

时间:2019-03-11 14:47:23

标签: mysql foreign-keys constraints

我正在尝试将语音中的PostDate引用到P_ASSIGNMENT中的PostDate,但这给了我"Error 1215: Cannot add foreign key constraint"。 我目前正在MySQL Workbench上使用InnoDB。

这是我的SQL代码:

CREATE TABLE P_ASSIGNMENT
(StaffID int not null,
 JobID int not null,
 PostDate date not null,
 EndDate date,
 CONSTRAINT P_Assignment_pk PRIMARY KEY (StaffID, JobID, PostDate),
);

CREATE TABLE SPEECH
 (EventName varchar(100) not null,
  EventDate date not null,
  OrderNum int not null,
  ContentAbst varchar(250),
  Contact int not null,
  Presenter int not null,
  JobID int not null,
  PostDate date not null,
 CONSTRAINT Speech_pk PRIMARY KEY (EventName, EventDate, OrderNum),
 CONSTRAINT Speech_fk3 FOREIGN KEY (Presenter) REFERENCES P_ASSIGNMENT (StaffID),
 CONSTRAINT Speech_fk4 FOREIGN KEY (JobID) REFERENCES P_ASSIGNMENT (JobID),
 CONSTRAINT Speech_fk5 FOREIGN KEY (PostDate) REFERENCES P_ASSIGNMENT(PostDate)
);

1 个答案:

答案 0 :(得分:0)

这是一个单个复合外键。语法为:

CREATE TABLE SPEECH
 (EventName varchar(100) not null,
  EventDate date not null,
  OrderNum int not null,
  ContentAbst varchar(250),
  Contact int not null,
  Presenter int not null,
  JobID int not null,
  PostDate date not null,
 CONSTRAINT Speech_pk PRIMARY KEY (EventName, EventDate, OrderNum),
 CONSTRAINT Speech_fk3 FOREIGN KEY (Presenter, JobID, PostDate) -- fix here
   REFERENCES P_ASSIGNMENT (StaffID, JobID, PostDate)
);

仅需说明一点,您就没有三个外键。您只有一个外键。该外键包含三列,因此是复合键。