#1072 - 关键栏' Customer_ID'表格中不存在

时间:2017-11-24 01:46:31

标签: mysql sql database

这是父表

CREATE TABLE Customer(
Customer_ID INT(5) not null,
CustName VARCHAR(50) not null,
CustSurname VARCHAR(50) not null,
CustEmail VARCHAR(100) unique not null,
CustMobileNo INT(12) not null,
HomeAddress VARCHAR(255) not null,
Password VARCHAR(10) not null,
constraint c_cuid_pk PRIMARY KEY (Customer_ID))
ENGINE = InnoDB;

当我尝试创建属性表时,它显示了我

  

"#1072 - 键列' Customer_ID'表"

中不存在

这是子表

CREATE TABLE Property(
Property_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
constraint p_phn_pk PRIMARY KEY (Property_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references IndividualCustomer(Customer_ID))
ENGINE = InnoDB;

3 个答案:

答案 0 :(得分:2)

在表Property中,您必须定义一个名为Customer_ID的列(它可以命名为任何内容!),然后在其上定义FOREIGN KEY

您的代码目前正尝试将IndificualCustomer(Customer_ID)Property(Customer_ID)相关联,但Property(Customer_ID)不存在。

声明约束只链接列,但它不会创建它们。

CREATE TABLE Property(
Property_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
Customer_ID INT(5) not null,
constraint p_phn_pk PRIMARY KEY (Property_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references IndividualCustomer(Customer_ID))
ENGINE = InnoDB;

答案 1 :(得分:1)

首先,您应该在Customer_ID表中添加一列Property来创建外键约束:

Property.Customer_ID → IndividualCustomer.Customer_ID

您不能对不存在的内容进行约束。 或者将表创建查询的+++ +++部分更改为存在的列。

constraint p_cuid_fk FOREIGN KEY (+++Customer_ID+++) --to be changed accordingly
references IndividualCustomer(Customer_ID)

示例:在表格声明中添加Customer_ID列会为您提供以下代码

CREATE TABLE Property(
Property_ID INT(5) not null,
Customer_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
constraint p_phn_pk PRIMARY KEY (Property_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references IndividualCustomer(Customer_ID))
ENGINE = InnoDB;

答案 2 :(得分:0)

CREATE TABLE Property(
Property_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
Customer_ID INT(5) not null,
PRIMARY KEY (Property_ID),
KEY p_cuid_fk (Customer_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references Customer(Customer_ID))
ENGINE = InnoDB;

您必须在表PROPERTY中添加Customer_ID。