[英]How to make primary key of one table, the foreign key of same table
How to make primary key of one table, the foreign key of the same table?如何使一张表的主键,同表的外键?
I have table vendors
with these attributes:我有具有以下属性的表vendors
:
vendor_id,
company_name
rep_first
rep_last
referredby
Do I want to make vendor_id
as the foreign key of that table?我想将vendor_id
作为该表的外键吗?
Here is what I have tried:这是我尝试过的:
create table vendors(
vendor_id char(5) Not Null primary key,
company_name varchar(255),
rep_first varchar(255),
rep_last varchar(255),
referredby char(5)
);
constraint vendors_REF_FK
foreign key (referredby) references vendors(referredby)
Constraints is also part of the table and thus have to go along with table definition like约束也是表格的一部分,因此必须与表格定义一起使用,例如
vendor_id char(5) Not Null primary key,
company_name varchar(255),
rep_first varchar(255),
rep_last varchar(255),
refferedby char(5),
constraint vendors_REF_FK foreign key (refferedby) references vendors(vendor_id ));
You may use ALTER TABLE
as well您也可以使用ALTER TABLE
ALTER TABLE Vendors
ADD CONSTRAINT vendors_REF_FK FOREIGN KEY (refferedby) REFERENCES Vendors(vendor_id );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.