复合键为空白,插入时约束失败

时间:2018-04-23 14:32:00

标签: mysql sql database

将数据插入到我的数据库中时出错。我想让EventStaff有一个主键,由StaffID.EventID组成,就像在底部的这个图中一样。我无法看到我做错了什么,因为StaffID中的表已填充并且在TypeID中。我试图创建两个不同表的复合键,这是错误的方法去>我已经使用了图表参考。

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`db`.`EventStaff`, CONSTRAINT `fStaff1` FOREIGN KEY (`StaffID`) REFERENCES `Staff` (`StaffID`))

这是数据库的代码

CREATE TABLE  EventType (
TypeID INT NOT NULL,
Description VARCHAR(200) NULL,
CONSTRAINT pEventType PRIMARY KEY (TypeID)
);
CREATE TABLE  Staff (
StaffID INT NOT NULL,
CONSTRAINT pStaff PRIMARY KEY (StaffID)
);

CREATE TABLE  Event (
EventID INT NOT NULL,
Description VARCHAR(500) NULL,
Name VARCHAR(100) NULL,
DateStart DATE NULL,
DateEnd DATE NULL,
TimeStart TIME NULL,
TimeEnd TIME NULL,
TypeID INT NULL,
ClientID INT NULL,
NoBands BOOLEAN NOT NULL,
MaxFoodStall INT NULL,
CONSTRAINT pEvent PRIMARY KEY (EventID),
CONSTRAINT fType1 FOREIGN KEY (TypeID) REFERENCES  EventType (TypeID),
);

CREATE TABLE  EventStaff (
StaffID int NOT NULL,
EventID int NOT NULL,
Role VARCHAR(45) NULL,
PRIMARY KEY (StaffID, EventID),
CONSTRAINT fStaff1 FOREIGN KEY (StaffID) REFERENCES  Staff (StaffID),
CONSTRAINT FEvent1 FOREIGN KEY (EventID) REFERENCES  Event (EventID)
);

以下是插入

insert into EventType (TypeID, Description) values (1, 'Intuitive attitude-oriented hierarchy');
insert into EventType (TypeID, Description) values (2, 'Mandatory executive concept');

insert into Staff (StaffID) values (1);
insert into Staff (StaffID) values (2);

 insert into Event (EventID, Description , DateStart, DateEnd, TimeStart, TimeEnd, NoBands, MaxFoodStall, Name) values (1, 'Cloned 6th generation pricing structure', '2018-03-13', '2018-07-20', '11:18 PM', '4:58 PM', false, 17, 'Swaniawski-Ankunding');
insert into Event (EventID, Description , DateStart, DateEnd, TimeStart, TimeEnd, NoBands, MaxFoodStall, Name) values (2, 'Ameliorated mission-critical throughput', '2017-10-11', '2019-01-05', '10:44 AM', '8:26 PM', true, 4, 'Langworth-Ferry');

  insert into EventStaff (Role) values ('Editor');
 insert into EventStaff (Role) values ('Budget/Accounting Analyst IV');

https://image.ibb.co/jwaxRx/problem.png

1 个答案:

答案 0 :(得分:0)

您发布到此问题的代码有拼写错误,甚至不会按原样运行。一旦我修复了这些,我就能够重现你的外键错误。问题实际上是由最后两个插入引起的:

INSERT INTO EventStaff (Role) VALUES ('Editor');
INSERT INTO EventStaff (Role) VALUES ('Budget/Accounting Analyst IV');

您没有指定StaffIDEventID的值,并且这些列已标记为不可为空。它们是外键,如果你没有将列标记为不可为空,它实际上可以插入NULL。这是让这个错误消失的一种方法:

INSERT INTO EventStaff (Role, StaffID, EventID)
    VALUES ('Editor', 1, 1);
INSERT INTO EventStaff (Role, StaffID, EventID)
    VALUES ('Budget/Accounting Analyst IV', 2, 2);

我不知道你打算插入什么值,但上面是一种方法。

请注意,在Event表的插入中,指定TypeID列的值,该列也是外键。但是,在这种情况下,您已将列标记为可为空,因此MySQL接受它。