Shr*_*ut1 4 foreign-key primary-key oracle-11g
我想构建一个由来自两个不同表的外键组成的复合主键。我对这个还是很绿的...
在这个问题上从多个外键构建复合键给出了一个很好的答案,但我想从多个表中执行此操作。我正在使用 Oracle 11g。
foreign key (Name, BoughtFrom, TimeBought)
references the_other_table_name (Name, BoughtFrom, TimeBought)
Run Code Online (Sandbox Code Playgroud)
想象一下,“references”行实际上包括多个表。我什至不确定上述语法是否适用于 Oracle。
我有一张桌子“学生”和一张桌子“家长”。这是一个多对多的关系。我的关联表名为“Relation”,我想从“PAR_ID”和“STU_ID”创建一个复合主键。两者都是外键。
精简版:
CREATE TABLE Relation
( stu_id INT NOT NULL REFERENCES Student,
par_id INT NOT NULL REFERENCES Parent,
PRIMARY KEY (stu_id, par_id)
) ;
Run Code Online (Sandbox Code Playgroud)
长版:
为什么要对名称使用缩写形式,例如stu_id
和par_id
?为什么不student_id
呢?节省输入 3-4 个字符?您将如何区分 parent_id 和 parameter_id?还是 school_id 和 schoolmaster_id?
该名称"Relation"
不是很能描述关系。(另请注意,在关系模型术语中,“关系”的含义与“表”非常接近。)不过我找不到好名字,所以我们可以使用"Guardian"
or "Student_Parent"
(这种组合经常用于交集表)
上面的简短版本只是一个例子。在工作时,它使用了很多快捷方式,例如内联引用。在我看来,在列声明之后命名所有约束并声明所有(主、唯一、外键和检查)约束要好得多,就像下面的长版本一样。
选择一些命名约定并在所有表中一致使用它们也很好,例如Tablename_PK
对于主键、ReferencedTable_referencingTable_FK
外键、Something_UQ
唯一约束等。
CREATE TABLE Guardian
( -- columns
student_id INT NOT NULL,
parent_id INT NOT NULL,
-- constraints
CONSTRAINT Guardian_PK -- the name of the PK constraint
PRIMARY KEY (student_id, parent_id),
CONSTRAINT Student_Guardian_FK -- the name of the FK constraint
FOREIGN KEY (student_id)
REFERENCES Student (student_id)
ON UPDATE CASCADE -- the actions of the FK
ON DELETE RESTRICT,
CONSTRAINT Parent_Guardian_FK -- second FK
FOREIGN KEY (parent_id)
REFERENCES Parent (parent_id)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ;
Run Code Online (Sandbox Code Playgroud)