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
Advertisement
Answer
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.