在 SQL 中使用外键

Using foreign keys in SQL

我想使用 'address' table 中的 'Postcode' 作为 'customers' table 中的主键作为外键。我对从租金table中获取'RentalID'作为'customers'table中的外键做了同样的事情,但是,当我尝试对'Postcode'做同样的事情时,它给出了我这个错误:“请检查父 table 地址 的 table 客户的外键约束”。

请注意我在 khanacademy.org

上使用在线 SQLite IDE

这是我的代码:

CREATE TABLE rentals 
( RentalID INTEGER PRIMARY KEY, CarRegistration TEXT, DateHired TEXT, 
DateReturned TEXT); 

INSERT INTO rentals VALUES (  1, "J986NDX", "12.2.94", "25.8.94"); 
INSERT INTO rentals VALUES (  2, "K788NRT", "1.3.95", "1.4.96"); 
INSERT INTO rentals VALUES (  3, "L346NDS", "2.4.96", ""); 
INSERT INTO rentals VALUES (  4, "J986NDX", "15.9.94", "14.9.95"); 
INSERT INTO rentals VALUES (  5, "M411NGT", "15.9.95", "1.2.96");  

CREATE TABLE customers (CustomerID INTEGER, CustomerSurname TEXT, 
Customerinitial TEXT, Companyname TEXT, Postcode TEXT, RentalID INTEGER , 
PRIMARY KEY(CustomerID, RentalID), FOREIGN KEY (RentalID) REFERENCES 
rentals(RentalID), FOREIGN KEY (Postcode) REFERENCES address(Postcode));

INSERT INTO customers VALUES ( 153, "Nazarali", "N", "MF Plastics", "DB5 
3ER", 1); 
INSERT INTO customers VALUES ( 153, "Nazarali", "N", "MF Plastics", "DB5 
3ER", 2); 
INSERT INTO customers VALUES ( 187, "Brown", "L", "MF Plastics", "DB5 3ER", 
3); INSERT INTO customers VALUES ( 287, "Pinner", "M", "Took Ltd", "DB6 
8YU", 4); INSERT INTO customers VALUES ( 287, "Pinner", "M", "Took Ltd", 
"DB6 8YU", 5);  

CREATE TABLE address (Postcode TEXT PRIMARY KEY, town TEXT);  
INSERT INTO address VALUES ( "DB5 3ER", "Derby"); 
INSERT INTO address VALUES ( "DB6 8YU", "Derby");

如何解决?

基本上我所要做的就是创建地址 table 并因此在我创建客户之前创建邮政编码值 table 因为你不能有一个属性的外键目前不存在,因为不会有任何限制。父 table 必须在客户 table 之前创建。

如果数据已经插入到外键 table 中,则外键有效,其中外键是 table 的主键。尝试做子查询(在插入语句中插入)