gpt4 book ai didi

mysql - 了解为什么外键引用同一张表中的主键?

转载 作者:可可西里 更新时间:2023-11-01 07:46:44 26 4
gpt4 key购买 nike

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 表

emp_id is primary key 

superior_emp_id 是一个外键 引用同一个表中的emp_id

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

最佳答案

这就是您创建层次结构的方式, 将确保您不能拥有没有 parent 的 child ,也可以确保您不能拥有无效 parent 的 child 。

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

关于mysql - 了解为什么外键引用同一张表中的主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7175410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com