问题描述
如何使用PostgreSQL在单个表中为多列提供主键?
How to provide primary key for multiple column in a single table using 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
Note: I want to make "EmpID"
also a primary key.
推荐答案
每个表只能有一个主键-如所示
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 automatically
emp_id int UNIQUE NOT NULL,
emp_name text,
emp_addr text
);
或者使单个,使用表约束代替列约束:
Or to make that a single multicolumn primary key, use a table constraint instead of a column constraint:
CREATE TABLE test(
sl_no int, -- NOT NULL automatically
emp_id int , -- NOT NULL automatically
emp_name text,
emp_addr text,
PRIMARY KEY (sl_no, emp_id)
);
(多列 UNIQUE
约束也是可能的。)
(Multicolumn UNIQUE
constraints are possible, too.)
此外:请勿在Postgres中使用CaMeL大小写标识符。使用合法的小写标识符,因此您不必使用双引号。使您的生活更轻松。
Aside: Don't use CaMeL-case identifiers in Postgres. Use legal, lower-case identifiers so you never have to use double-quotes. Makes your life easier.
这篇关于PostgreSQL中多列的主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!