[英]SQL: Having a primary key also be a foreign key
For this question, I am referring to the specific case where you have table T, it has primary key K, but K is a foreign key . 对于这个问题,我指的是您拥有表T的特定情况,表T具有主键K,但是K是外键 。 Is this valid? 这有效吗? And how would you write it in SQL99? 以及如何在SQL99中编写它?
All the other questions I've seen on here are just asking whether or not a primary key can be a foreign key for another table. 我在这里看到的所有其他问题都只是在询问主键是否可以是另一个表的外键。 That's not what I'm asking about. 那不是我要问的。 I'm asking about a table which has a foreign key where that is the primary key of that table. 我问其中有一个外键,其中是该表的主键的表。
If I understand you correctly, you want to create a hierarchical table, for instance: 如果我对您的理解正确,那么您想创建一个层次表,例如:
create table hierarchical
(
id number primary key,
parent_id number
);
alter table hierarchical add constraint
fk_parent_id foreign key(parent_id) references hierarchical(id);
This kind of table can contain employees/managers for instance. 例如,这种表可以包含员工/经理。
A column can be a primary key as well foreign key. 列可以是主键,也可以是外键。 For example, refer to the following: 例如,参考以下内容:
A column can be both a primary key and a foreign key. 列既可以是主键,也可以是外键。 For example: 例如:
create table A
(
id int not null
, constraint PK_A primary key (id)
);
create table B
(
id int not null
,constraint PK_B primary key (id)
,constraint FK_B_ID foreign key (id) references A(id)
);
Though, this requires data to be present in Table B first. 但是,这要求数据首先出现在表B中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.