PostgreSQL 中多列的主键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23533184/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:26:22  来源:igfitidea点击:

Primary key for multiple column in PostgreSQL?

postgresqldatabase-designprimary-keyddlcomposite-primary-key

提问by Meem

How to provide primary key for multiple column in a single table using PostgreSQL?

如何使用 PostgreSQL 为单个表中的多列提供主键?

Example:

例子:

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
);

Note: I want to make "EmpID"also a primary key.

注意:我还想制作"EmpID"一个主键。

回答by Erwin Brandstetter

There can only be oneprimary key per table - as indicated by the word "primary".

每个表只能有一个主键 - 如“primary”一词所示。

You can have additional UNIQUEcolumnslike:

您可以有其他UNIQUE列,例如:

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 multicolumnprimary 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)
);

(Multicolumn UNIQUEconstraints are possible, too.)

(多列UNIQUE约束也是可能的。)

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.

旁白:不要在 Postgres 中使用 CaMeL-case 标识符。使用合法的小写标识符,这样您就不必使用双引号。让您的生活更轻松。