为什么因为外键错误而无法添加此条目?

时间:2016-02-03 18:07:16

标签: mysql

我在尝试向其中一个表添加条目时一直收到此错误。

'(`coursework1`.`ROUTE`,
   CONSTRAINT `FK_ROUTE_DELIVERY`
   FOREIGN KEY (`DELIVERY_VEHICLE_VEH_ID`)
   REFERENCES `DELIVERY` (`VEHICLE_VEH_ID`))'

尝试添加此代码:INSERT INTO ROUTE VALUES ('7418','66','200','313');
进入这个表:

CREATE TABLE ROUTE (
 ROUTE_ID INT NOT NULL PRIMARY KEY,
 ROUTE_NAME VARCHAR(45) NOT NULL,
 DELIVERY_VEHICLE_VEH_ID INT NOT NULL,
 DELIVERY_DRIVER_DR_ID INT NOT NULL,
 CONSTRAINT FK_ROUTE_DELIVERY FOREIGN KEY (DELIVERY_VEHICLE_VEH_ID)
     REFERENCES DELIVERY (VEHICLE_VEH_ID),
 FOREIGN KEY (DELIVERY_DRIVER_DR_ID) REFERENCES DELIVERY (DRIVER_DR_ID));

给出错误:

CANNOT ADD OR UPDATE A CHILD ROW: A FOREIGN KEY CONSTRAINT FAILS:
(coursework1.ROUTE, CONSTRAINT FK_ROUTE_DELIVERY FOREIGN KEY
    (DELIVERY_VEHICLE_VEH_ID) REFERENCES DELIVERY (VEHICLE_VEH_ID))

其他相关表格

CREATE TABLE DELIVERY (
VEHICLE_VEH_ID INT NOT NULL,
DRIVER_DR_ID INT NOT NULL,
DEL_DATE DATETIME NOT NULL,
DEL_TIME DATETIME NOT NULL,
PRIMARY KEY (VEHICLE_VEH_ID , DRIVER_DR_ID),
INDEX (DRIVER_DR_ID),
INDEX (VEHICLE_VEH_ID),
CONSTRAINT FK_VEHICLE_HAS_DRIVER_VEHICLE FOREIGN KEY (VEHICLE_VEH_ID) REFERENCES VEHICLE (VEH_ID), 
CONSTRAINT FK_VEHICLE_HAS_DRIVER_DRIVER FOREIGN KEY (DRIVER_DR_ID) REFERENCES DRIVER (DR_ID));

CREATE TABLE DRIVER (
 DR_ID INT NOT NULL PRIMARY KEY,
 DR_TITLE VARCHAR(15) NOT NULL,
 DR_FNAME VARCHAR(45) NOT NULL,
 DR_LNAME VARCHAR(45) NOT NULL,
 DR_DOB DATETIME NOT NULL,
 DR_LICENCENO VARCHAR(45) NOT NULL,
 DR_PHONE VARCHAR(15) NOT NULL,
 DR_EMAIL VARCHAR(45) NOT NULL);

1 个答案:

答案 0 :(得分:2)

当您尝试插入此记录时:

INSERT INTO ROUTE VALUES ('7418','66','200','313');

您假设DELIVERY中的值为VEHICLE_VEH_ID '200'DELIVERY_DRIVER_DR_ID值为'313'。有错误告诉你该表中没有这样的记录。

外键约束意味着具有该约束的列约束仅指向外表中的有效记录。 (在这种情况下为DELIVERY。)在此表中必须存在此类记录,然后才能在此表中插入从属记录。