简体   繁体   English

创建SQL表时,外键约束中引用的列“parent_id”不存在

[英]column “parent_id” referenced in foreign key constraint does not exist when creating SQL table

I am new in SQL and trying to understand Foreign key syntax.我是 SQL 新手并试图理解外键语法。 I know this was asked in multiple questions but each question I found did not seem to teach me what I am doing wrong here.我知道这是在多个问题中被问到的,但我发现的每个问题似乎都没有告诉我我在这里做错了什么。 This is my SQL code:这是我的 SQL 代码:

CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,
gender bool
);

CREATE TABLE Minor
(
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);

CREATE TABLE Adult
(
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);

CREATE TABLE Shop
(
id int primary key
);

CREATE TABLE Drink
(
name varchar(30) primary key
);

CREATE TABLE AlcoholicDrink
(
FOREIGN KEY (name) REFERENCES Drink(name)
);

CREATE TABLE NonAlcoholicDrink
(
FOREIGN KEY (name) REFERENCES Drink(name)
);

And this is the error I am getting:这是我得到的错误:

ERROR:  column "parent_id" referenced in foreign key constraint does not exist
SQL state: 42703

You need to add fields in your tables to make the reference.您需要在表中添加字段以进行引用。 Something like this :像这样的事情:

CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,
gender bool
);

CREATE TABLE Minor
(
minor_id serial primary key,
parent_id int,
other_fields text etc.
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);

This is simply the reason why it's not working.这只是它不起作用的原因。

Like this像这样

CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,  
gender bool
);
CREATE TABLE Minor
(
parent_id int ,
FOREIGN KEY (parent_id) REFERENCES Customer(id)
);

To add an answer without just a code snippet:要添加不只是代码片段的答案:

You've got the right idea with FOREIGN KEY (parent_id) REFERENCES Customer(id) .您对FOREIGN KEY (parent_id) REFERENCES Customer(id)想法是正确的。 This bit adds a constraint or a "rule" to your table.此位为您的表添加了约束或“规则”。 This constraint ensures that parent_id holds a real id in your Customer table.此约束确保parent_id在您的Customer表中保存一个真实的id

The error message told us that column "parent_id" referenced in foreign key constraint does not exist .错误消息告诉我们column "parent_id" referenced in foreign key constraint does not exist The confusion comes, understandably, from mistaking the constraint declaration for a column declaration.可以理解,混淆来自将约束声明误认为列声明。

As others have pointed out, we need to both 10 declare the foreign key constraint and 2) declare the column.正如其他人指出的那样,我们需要 10 声明外键约束和 2) 声明列。

CREATE TABLE Customer
(
id int primary key,
name varchar(30),
age int,  
gender bool
);
CREATE TABLE Minor
(
parent_id int, -- Declare the column
FOREIGN KEY (parent_id) REFERENCES Customer(id) -- Declare the constraint
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM