[英]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. Tom在这里只能使用B1和B3进入
StudentBranches
表,因为他属于Prog1,它是B1的程序。 And Bob can only enter to B2. 而鲍勃只能进入B2。
This cannot be validated directly through a constraint, since it affects multiple tables. 由于这会影响多个表,因此无法直接通过约束进行验证。 You're probably looking for a trigger on insert instead.
您可能正在寻找插入触发器 。
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: 如果您将每个表限制为仅表示1个事物,则应该更容易理解所有内容,即:
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)
);
StudentBranches
. StudentBranches
加入。 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. StudentBranches
删除了PRIMARY KEY
,因为您以前对“获取整列”的评论听起来像是学生应该可以注册多个程序。 If a student can register to exactly 1 program, then you need to add it back.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.