我使用引用它们的外键约束创建最终表之前所需的信息填充了所有数据库但是当我使用select * from mytbl查看最终表时,我的外键值将返回为空值。我一直在浏览这个网站和我的教科书一小时试图找出我的错误,但我没有看到它。这是我用于数据库的代码。
Create Database Donutsrus;
Create table customer
(CustomerID int not null auto_increment,
FirstName varchar(255) not null,
LastName varchar(255) not null,
StreetAddress char(255) not null,
Apartment varchar(255) not null,
City varchar(255) not null,
State varchar(2) not null,
ZipCode int(9) not null,
HomePhone int(10) not null,
MobilePhone int(10) not null,
OtherPhone int(10) not null,
Primary Key (CustomerID));
insert into Customer
(FirstName, LastName, StreetAddress, Apartment, City, State,
ZipCode, HomePhone, MobilePhone, OtherPhone)
Values ("Ken", "Weger", "StreetAddress", "Apartment", "City",
"ST", 123456789, 1111111111, 222222222, 333333333);
Create Table Donut
(Quantity int(255) not null,
DonutID int(255) not null auto_increment,
Name varchar(255) not null,
Description varchar(255) not null,
UnitPrice decimal(3,2) not null,
LineTotal Decimal(10,2) not null,
Primary Key (DonutID));
insert into Donut (Quantity, Name, Description, UnitPrice, LineTotal)
Values ("1", "Plain", "Plain Donut", "1.50", "1.50"),
("5", "Glazed", "Glazed Donut", "1.75", "8.75"),
("12", "Cinnamon", "Cinnamon Donut", "1.75", "21.00"),
("3", "Chocolate", "Chocolate Donut", "1.75", "5.25"),
("4", "Sprinkle", "Sprinkle Donut", "1.75", "7.00"),
("5", "Gluten-Free", "Gluten-Free Donut", "2.00", "10.00");
Create Table DonutOrder
(DonutOrderID int(255) not null auto_increment,
CustomerID int(255),
DonutID int(255),
`Date` date not null,
SpecialHandlingNotes Varchar(255),
Primary Key (DonutOrderID),
Index Customer (customerid),
Foreign Key (CustomerID) References Customer(CustomerID),
Index Donut (donutid),
Foreign Key (DonutID) References Donut(DonutID));
Insert into DonutOrder (`Date`, SpecialHandlingNotes)
Values ("20140506", "Please Include Plates and Napkins");
如果我在donidd数据库中的customerid和donutid之后添加一个非空语法我得到了这个
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`donutsrus`.`donutorder`, CONSTRAINT `donutorder_ibfk_1` FOREIGN KEY (`CustomerID`) REFERENCES `customer` (`CustomerID`)).
答案 0 :(得分:0)
您应该插入外键字段的值。例如:
Insert into DonutOrder (
`Date`,
SpecialHandlingNotes,
CustomerId,
DonutId
)
values ( "20140506",
"Please Include Plates and Napkins",
(select CustomerId from Customer where MobilePhone = 222222222),
(select DonutId from Donut where Name = 'Plain')
);