mysql 尝试将多个外键添加到单个表时出错

nue99wik  于 2022-11-28  发布在  Mysql
关注(0)|答案(1)|浏览(164)

我试图创建一个约束父表中3个外键的子表,但收到错误 *1215:无法添加外键约束 *
父表:

CREATE TABLE `Availability` (
   `time_of_day` varchar(20) NOT NULL,
   `day_of_week` varchar(20) NOT NULL,
   `email` varchar(60) NOT NULL,
   PRIMARY KEY (`time_of_day`,`day_of_week`,`email`),
   KEY `email` (`email`),
   CONSTRAINT `Availability_ibfk_1` FOREIGN KEY (`email`) REFERENCES `service_provider` (`email_service_provider`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8

子表(由于上述错误,我无法构建):

CREATE TABLE TEST1
(
  num_request INT NOT NULL,
  time_of_day VARCHAR(20) NOT NULL,
  day_of_week VARCHAR(20) NOT NULL,
  email VARCHAR(60) NOT NULL,
    PRIMARY KEY (num_request),
    Foreign key (time_of_day) references Availability(time_of_day),
    Foreign key (day_of_week) references Availability(day_of_week),
    Foreign key (email) references Availability(email)
  );

请告诉我我做错了什么...谢谢大家。

8xiog9wr

8xiog9wr1#

当您为具有复合主键(即多列的键)的表创建外键时,也应该将外键创建为复合的。

CREATE TABLE TEST1
(
  num_request INT NOT NULL,
  time_of_day VARCHAR(20) NOT NULL,
  day_of_week VARCHAR(20) NOT NULL,
  email VARCHAR(60) NOT NULL,
    PRIMARY KEY (num_request),
    Foreign key (time_of_day, day_of_week, email) references Availability(time_of_day, day_of_week, email)
)

外部索引键的数据行应该符合其所指涉的主索引键或唯一索引键的数据行。它们应该具有相同的数据行数目和相同的顺序。
您尝试做的是创建三个单独的约束,每个约束一列。

相关问题