create table d(id numeric(1), code varchar(2))
创建上表后,如何在两个字段和外键上添加复合主键?
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.
In Oracle, you could do this:
create table D (
ID numeric(1),
CODE varchar(2),
constraint PK_D primary key (ID, CODE)
);
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
.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.