postgresql Primary keys

一个表里面只能存在一个主键,但是可以有多个外键。在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




转载于:https://my.oschina.net/websec/blog/371488

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值