了解为什么外键在同一个表中引用主键?

时间:2011-08-24 12:28:41

标签: mysql sql database database-design

create table employee
 (emp_id smallint unsigned not null auto_increment,
  fname varchar(20) not null,
  lname varchar(20) not null,
  start_date date not null,
  end_date date,
  superior_emp_id smallint unsigned,
  dept_id smallint unsigned,
  title varchar(20),
  assigned_branch_id smallint unsigned,
  constraint fk_e_emp_id 
    foreign key (superior_emp_id) references employee (emp_id),
  constraint fk_dept_id
    foreign key (dept_id) references department (dept_id),
  constraint fk_e_branch_id
    foreign key (assigned_branch_id) references branch (branch_id),
  constraint pk_employee primary key (emp_id)
 );

我正在研究这个Example,我注意到employee table

emp_id is primary key 

superior_emp_id which is a foreign key引用同一个表中的emp_id

在同一个表中创建引用主键的外键为什么这样的数据库设计可以帮助我?

2 个答案:

答案 0 :(得分:8)

这就是你如何创建一个层次结构,将确保你没有一个没有父母的孩子也可以确保你不能让一个孩子的父母无效。

另见Should you make a self-referencing table column a foreign key?

答案 1 :(得分:6)

它应该表明一个员工可以有一个优越的

emp_id, fname, lname, superior_emp_id
----------------------
1, 'Big', 'Boss', null,
2, 'Viswanathan', 'Iyer', 1
在这个例子中,Big Boss是你的老板,他自己也没有老板。

相关问题