开发者

Understanding why Foreign key references to Primary key in the same table?

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)
 );

I'm studying this Example and i noticed in employee table

emp_id is primary key 

and superior_emp_id which is a foreign key references to the emp_id in the same table

creating foreign key which references to primary key in the same table why such a database design can any one help me ?


Thats how you would create a hierarchy, and would ensure that you can't have a child with no parent could also ensure you can't have a child with an invalid parent.

See also Should you make a self-referencing table column a foreign key?


It's supposed to indicate that an empolyee can have a superior

emp_id, fname, lname, superior_emp_id
----------------------
1, 'Big', 'Boss', null,
2, 'Viswanathan', 'Iyer', 1

in this example Big Boss is your boss, and he himself has no bosses above him.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜