MySQL错误代码1452.更改表以添加外键

时间:2014-10-21 03:32:51

标签: mysql foreign-keys alter-table mysql-error-1452

我删除了外键约束以添加数据,然后我后来更改了表以重新添加外键。但是,如果一个特定的表被更改,我会不断收到1452错误代码。

数据

INSERT INTO Invoice
values
(323, 'Head Injury Patient', 'Surgery and Bed Stay', 150.00, 918),
(543, 'Eye Injury Patient', 'Medicine and hourly eye drops', 50.00, 910),
(859, 'Leg Injury Patient', 'Surgery and Bed Stay', 100.00, 915);

添加外键

Alter table Invoice
Add Foreign Key(Medicine_ID) References Medicine(Medicine_ID);

构建发票

Create table Invoice (
Invoice_ID INT,
Invoice_description varchar(150),
Treatment varchar (150) NOT NULL,
Hospital_Cost INT NOT NULL,
Medicine_ID INT,
Primary Key(Invoice_ID)
);

医学建设

Create table Medicine (
Medicine_ID INT,
Medicine_name varchar(150),
Medicine_cost INT NOT NULL,
Medicine_description Varchar (150),
Brand_name varchar(150),
Manufacturer varchar(150),
Generic_name varchar(150),
price_per_unit INT,
Quantity_in_stock INT,
Primary Key(Medicine_ID)
);

1 个答案:

答案 0 :(得分:1)

我认为错误意味着Invoice表中有一行Medicine_ID表中没有Medicine值。

要确定Invoice表中不存在Medicine中的哪些值,请尝试以下查询:

SELECT
    i.*
FROM
    Invoice i
    LEFT JOIN Medicine m
        ON i.Medicine_ID = m.Medicine_ID
WHERE
    m.Medicine_ID IS NULL

您必须将相应的行添加到Medicine表中,或者从Invoice表中删除这些行。