存在的外键取决于2个主键?

时间:2013-12-06 13:30:57

标签: c# sql

作为问题标题。示例:我有3名员工,老师,学生。

一名员工的外键取决于学生的PRIMARY KEY

一名员工的外国钥匙依赖教师的主要钥匙

我试过但我不能。

3 个答案:

答案 0 :(得分:1)

据我了解你的问题:

1个外键可以指2个不同的表吗?

答案:不,它不能。

您可以(也可能应该)轻松定义2个单独的外键:

  • 员工IS |有学生
  • 员工IS | HAS老师

答案 1 :(得分:0)

您无法将外键链接到两个表。

如果您可以控制表结构,那么拥有不同的结构可能更有意义

table: Person
table: EmployeeInfo (all information about being an employee i.e. EmpNo, ClockNo etc) with a foreign key on Person
table: TeacherInfo (all information about being a teacher i.e. HomeRoom, subject etc) with a foreign key on Person
table: StudentInfo (all information about a student i.e. course, funding type etc) with a foreign key on Person

通过一些简单的连接,您可以获得所有员工的老师,或所有员工的学生,或者既不是教师也不是学生的所有员工

答案 2 :(得分:0)

执行此操作的一种方法是创建一个人员表,该人员表是父表,然后是子表,学生,教师和员工可以使用从主键到人员表的外键。例如:

CREATE TABLE people
(
  id bigserial NOT NULL,
  first_name character varying(128) NOT NULL,
  last_name character varying(128) NOT NULL,
   -- other columns appropriate to a person
  CONSTRAINT people_pk PRIMARY KEY (id)
)


CREATE TABLE students
(
  fk_person bigint NOT NULL,
   -- other columns appropriate to the student
  CONSTRAINT students_pk PRIMARY KEY (fk_person),
  CONSTRAINT students_fk FOREIGN KEY (fk_person)
  REFERENCES people (id) MATCH SIMPLE
  ON UPDATE NO ACTION ON DELETE NO ACTION
)

CREATE TABLE teachers
(
  fk_person bigint NOT NULL,
   -- other columns appropriate to the teacher
  CONSTRAINT teachers_pk PRIMARY KEY (fk_person),
  CONSTRAINT teachers_fk FOREIGN KEY (fk_person)
  REFERENCES people (id) MATCH SIMPLE
  ON UPDATE NO ACTION ON DELETE NO ACTION
)

CREATE TABLE employees
(
  fk_person bigint NOT NULL,
   -- other columns appropriate to the employee
  CONSTRAINT employees_pk PRIMARY KEY (fk_person),
  CONSTRAINT employees_fk FOREIGN KEY (fk_person)
  REFERENCES people (id) MATCH SIMPLE
  ON UPDATE NO ACTION ON DELETE NO ACTION
)

您还可以向人员添加一个鉴别器列,以便您区分学生和教师,以及对员工中的鉴别器列进行检查(或触发),以确保只有教师和学生放在该表中。有关鉴别器列的更多信息,请查看hibernate documents