简体   繁体   English

一个外键和两个主键

[英]one foreign key and two primary keys

I have an assignment table and an employee table. 我有一个工作分配表和一个雇员表。 I want an assignment to be associated with an existing employee and an existing project. 我希望将工作分配与现有员工和现有项目相关联。 I have two primary keys, one from the employee table and the other from the project table. 我有两个主键,一个来自employee表,另一个来自项目表。 Each referencing back to the assignment table. 每个引用都返回到分配表。 May my foreign key constraints be separate as I show or do they have to be together and have an 'and' statement? 我的外键约束是否可以像我展示的那样分开,或者它们必须在一起并带有“ and”语句?

 create table assignment 
(asg_prj_p# number(2),
asg_emp_e#a varchar2(1),
asg_emp_e#n varchar2(5),
asg_hrs number(3),
constraint fk_project foreign key (asg_prj_p#) references project (prj_p#),
constraint fk_employee foreign key (asg_emp_e#a, asg_emp_e#n) references employee (emp_e#a, emp_e#n));

Your question is not fully clear to me. 您的问题对我来说还不是很清楚。 But the following statements will help you to solve the question. 但是以下陈述将帮助您解决问题。

In you assignment table you have two foreign key. 在分配表中,您有两个外键。 One is single foriegn key: asg_prj_p# and another one is composite foreign key (asg_emp_e#a, asg_emp_e#n). 一个是单foriegn键:asg_prj_p#,另一种是复合外键(asg_emp_e#一,asg_emp_e#N)。 The composite foreign key must refer to a composite primary key or composite Unique key columns. 复合外键必须引用复合主键或复合唯一键列。 So in your example the (emp_e#a, emp_e#n) columns of employee table must be a composite primary key or composite unique key. 因此,在您的示例中,employee表的(emp_e#a,emp_e#n)列必须是复合主键或复合唯一键。

The foreign key constraints are independent- ie one ensures you have a row in the project table with the ID specified in your asg_prog_p field, the other does the same re the employee table and the two fields that make up a key to it. 外键约束是独立的,即一个确保您在项目表中有一行,其ID在asg_prog_p字段中指定,另一个确保对employee表的操作相同,而两个字段构成了该键的键。 So what you have looks good, in terms of foreign key constraints. 因此,就外键约束而言,您看起来不错。

You may then want a composite primary key using these 3 fields- that depends on whether an employee can have one or more assignments on a particular project. 然后,您可能需要使用这3个字段的组合主键-这取决于员工是否可以在特定项目上进行一项或多项任务。 If one only then a composite primary key might be a good idea. 如果只有一个,则复合主键可能是一个好主意。 Otherwise you should consider if you need another field to join the composite primary key, or you could create a new field, eg 'assignment_id' to be the primary key. 否则,您应该考虑是否需要另一个字段来加入组合主键,或者可以创建一个新字段,例如将“ assignment_id”作为主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM