简体   繁体   中英

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. 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:

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) . 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.

The error message told us that 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.

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
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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