一个表里面只能存在一个主键,但是可以有多个外键。在pg中建议每个表都设置主键,但是这并不强制。
主键的创建方法:
1.表约束.
create table product (
product_no integer,
b integer,
c integer,
price numeric,
name text,
constraint product_no_pkey primary key(product_no)
);
上面的product_no_pkey是一个别名。
2.字段约束
create table product (
product_no integer primary key,
b integer,
c integer
price numeric,
name text
)
字段约束的创建是在你需要创建为主键的字段后面加上primary key就可以了,同样的你也可以给他起一个别名
create table product (
product_no integer constraint test_key primary key, --test_key在这里就是一个别名
b integer,
c integer,
price numeric,
name text
)
在官方文档上面有一句话:
Technically, a primary key constraint is simply a combination of a unique constraint and a not-null constraint.
翻译:从技术上来说, 主键就是唯一约束与非空约束的组合
create table product3(
product_no integer unique not null ,
b integer,
c integer,
price numeric,
name text
)
create table product3(
product_no integer primary key,
b integer,
c integer,
price numeric,
name text
)
上面两个是等价的。
但是一个表里面只能拥有一个主键。
create table product3(
product_no integer unique not null ,
b integer unique not null,
c integer,
price numeric,
name text
)
create table product3(
product_no integer primary key ,
b integer primary key,
c integer,
price numeric,
name text
)
就好比是上的两个例子一样,第二例子是不能通过。
会提示错误:
ERROR: multiple primary keys for table "product3" are not allowed
SQL 状态: 42P16