如何使用PostgreSQL为单个表中的多个列提供主键?
例子:
Create table "Test"
(
"SlNo" int not null primary key,
"EmpID" int not null, /* Want to become primary key */
"Empname" varchar(50) null,
"EmpAddress" varchar(50) null
);
注:我想让"EmpID"
也成为主键.
如何使用PostgreSQL为单个表中的多个列提供主键?
例子:
Create table "Test"
(
"SlNo" int not null primary key,
"EmpID" int not null, /* Want to become primary key */
"Empname" varchar(50) null,
"EmpAddress" varchar(50) null
);
注:我想让"EmpID"
也成为主键.
There can only be one primary key per table - as indicated by the word "primary".
You can have additional UNIQUE
columns like:
CREATE TABLE test(
sl_no int PRIMARY KEY, -- NOT NULL due to PK
emp_id int UNIQUE NOT NULL,
emp_name text,
emp_addr text
);
属于PRIMARY KEY
的列将自动标记为NOT NULL
.
或者使用表约束而不是列约束来创建单个multicolumn primary key.这在语义上与上面的不同:现在,只有两列中的combination列必须是唯一的,每列可以单独保存重复项.
CREATE TABLE test(
sl_no int, -- NOT NULL due to PK below
emp_id int , -- NOT NULL due to PK below
emp_name text,
emp_addr text,
PRIMARY KEY (sl_no, emp_id)
);
多列UNIQUE
约束也是可能的.
旁白:不要在Postgres中使用驼峰大小写标识符.使用合法的小写标识符,这样就不必使用双引号.让你的生活更轻松.见: