SQL 如何将复合主键添加到表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1350990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add composite primary key to table
提问by Domnic
create table d(id numeric(1), code varchar(2))
After I create the above table how can I add a composite primary key on both fields and also a foreign key?
创建上表后,如何在两个字段和外键上添加复合主键?
回答by Chris W
alter table d add constraint pkc_Name primary key (id, code)
alter table d add constraint pkc_Name primary key (id, code)
should do it. There's lots of options to a basic primary key/index depending on what DB your working with.
应该这样做。根据您使用的数据库,基本主键/索引有很多选项。
回答by Simon Nickerson
In Oracle, you could do this:
在 Oracle 中,您可以这样做:
create table D (
ID numeric(1),
CODE varchar(2),
constraint PK_D primary key (ID, CODE)
);
回答by Thilo
The ALTER TABLE
statement presented by Chris should work, but first you need to declare the columns NOT NULL
. All parts of a primary key need to be NOT NULL
.
ALTER TABLE
Chris 提出的语句应该有效,但首先您需要声明 columns NOT NULL
。主键的所有部分都必须是NOT NULL
.
回答by Jon Crowell
You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:
您无需先创建表,然后在后续步骤中添加键。您可以在创建表时添加主键和外键:
This example assumes the existence of a table (Codes
) that we would want to reference with our foreign key.
此示例假设存在Codes
我们希望使用外键引用的表 ( )。
CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)
If you don't have a table that we can reference, add one like this so that the example will work:
如果您没有可供我们参考的表格,请添加这样的表格,以便示例能够正常工作:
CREATE TABLE Codes (
Code [varchar](2) PRIMARY KEY
)
NOTE:you must have a table to reference before creating the foreign key.
注意:在创建外键之前,您必须有一个要引用的表。