Primary key for multiple column in PostgreSQL?

流过昼夜 提交于 2020-01-22 11:46:26

问题


How to provide primary key for multiple column in a single table using 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.


回答1:


There can only be one primary key per table. That's what the word "primary" hints at.

You can have additional UNIQUE columns.

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

Aside: My advice is not to use CaMeL-case identifiers in Postgres. Ever. Makes your life easier.



来源:https://stackoverflow.com/questions/23533184/primary-key-for-multiple-column-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!