A FK constraint requires a UNIQUE or PK constraint on the target column(s), which schoolname
obviously cannot provide. You need another table with unique rows per school:
CREATE TABLE school(
school_id serial PRIMARY KEY,
schoolname text NOT NULL
);
CREATE TABLE student(
student_id serial PRIMARY KEY,
studentname text
);
CREATE TABLE schoolstudent(
school_id int REFERENCES school,
student_id int REFERENCES student,
PRIMARY KEY (school_id, student_id)
);
CREATE TABLE course(
course_id text PRIMARY KEY,
school_id int REFERENCES school
);
Using short syntax for foreign key constraints. Details in the manual.
If you really need schoolname
in the schoolstudent
table (I seriously doubt that, looks like a design error), you can just add it. To enforce referential integrity you can include it in the foreign key, but you need a (redundant) matching UNIQUE
constraint on school(school_id, schoolname)
, too.
CREATE TABLE schoolstudent(
school_id int,
student_id int REFERENCES student,
schoolname text,
PRIMARY KEY (school_id, student_id),
CONSTRAINT schoolstudent_combo_fk FOREIGN KEY (school_id, schoolname)
REFERENCES school (school_id, schoolname) ON UPDATE CASCADE
);
Using explicit syntax in this case. And I suggest to cascade updates.
Or if schoolname
is actually guaranteed to be UNIQUE
(again, my doubts) you can replace school_id
completely and just use schoolname
as PK and FK column. Long text
columns are not very efficient for the purpose, though - if performance matters. And schoolnames change, which is not ideal for PK columns.
You still need a separate school
table in any case.