2014-01-10 32 views
0

這是我正在使用的一些表格的一個例子。如何在插入數據時確保外鍵作爲另一個表中的主鍵存在?

create TABLE People(
peopleID int not null, 
name varchar(40) not null, 
primary key (peopleID) 
); 


create table car(
carID int not null, 
peopleID int not null, 
primary key (carID), 
foreign key (peopleID) references People(peopleID) 
); 

我如何確保當我插入「車」,將「的peopleid」外鍵的存在,如表中「人」主鍵。

例如,我想下面的語句拋出一個錯誤:

INSERT INTO car VALUES (123, 343); 

...因爲343不「的peopleid」存在,因爲它是空的。

謝謝

回答

1

這是有點長的評論。

你描述一下foreign key約束確實

For storage engines supporting foreign keys, MySQL rejects any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.

約束描述here

+0

謝謝,我已經解決了這個問題。 – user2891805

相關問題