Skip to content
Advertisement

How do I make a foreign key reference to a specific cell when the primary key is known in sql?

I’ve been searching and tackling this for hours and I’m sure there’s a super easy way to do this.

I have two tables:

CREATE TABLE Students 
(
    idnr            NUMERIC(10) PRIMARY KEY,
    name            TEXT        NOT NULL,
    login           TEXT        NOT NULL,
    program         TEXT        NOT NULL 
);

CREATE TABLE Branches
(
    name            TEXT,
    program         TEXT,
    PRIMARY KEY(name, program) 
);

And in a third table, I want to make sure that the “program” is the same for the student and the branch.

CREATE TABLE StudentBranches 
(
    student         NUMERIC(10) PRIMARY KEY REFERENCES Students(idnr),
    branch          TEXT        NOT NULL,
    program         TEXT        NOT NULL,
    FOREIGN KEY (branch, program) REFERENCES Branches(name, program),
    FOREIGN KEY (student, program) REFERENCES Students(idnr, program) 
);

The problem I run in to is that this tries to get the whole column from program in Students. I only want the value for said student not the whole column.

To clarify:

Students:

idnr | name | login | program
-----+------+-------+-----------
1234 | bob  | 1111  | prog1
2222 | tom  | 2222  | prog2

Branches:

branch  | program
--------+---------
branch1 | prog1
branch2 | prog2
branch3 | prog1 

Here Tom should only be able to enter the StudentBranches table with B1 and B3, since he belongs to Prog1 that is a program for B1. And Bob can only enter to B2.

Advertisement

Answer

As I said in my comment, it’s hard to tell what you’re trying to do but the foreign keys you’ve tried to create definitely look fishy.
Everything should be easier to understand if you limit each table to represent 1 thing only, that is respectively:

  • A student (without the attached program since that would be 2 things for the same table).
  • A program/branch (whatever you call it)
  • The link from a student to a branch.

This results in:

CREATE TABLE Students (
    idnr            NUMERIC(10) PRIMARY KEY,
    name            TEXT        NOT NULL,
    login           TEXT        NOT NULL
);

CREATE TABLE Branches(
    name            TEXT,
    program         TEXT,
    PRIMARY KEY(name, program)
);

CREATE TABLE StudentBranches (
    student         NUMERIC(10) REFERENCES Students(idnr),
    branch          TEXT        NOT NULL,
    program         TEXT        NOT NULL,
    FOREIGN KEY (branch, program) REFERENCES Branches(name, program)
);
  • To fetch the program a student as registered to, you have to JOIN with StudentBranches.
  • I have removed the PRIMARY KEY from StudentBranches because your previous comment about “get the whole column” sounded like a student should be able to register to more than 1 program. If a student can register to exactly 1 program, then you need to add it back.
8 People found this is helpful
Advertisement