加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql Primary keys

发布时间:2020-12-13 17:22:37 所属栏目:百科 来源:网络整理
导读:一个表里面只能存在一个主键,但是可以有多个外键。在pg中建议每个表都设置主键,但是这并不强制。 主键的创建方法: 1. 表约束 . createtableproduct(product_nointeger,binteger,cinteger,pricenumeric,nametext,constraintproduct_no_pkeyprimarykey(prod

一个表里面只能存在一个主键,但是可以有多个外键。在pg中建议每个表都设置主键,但是这并不强制。

主键的创建方法:

1.表约束.

createtableproduct(
product_nointeger,binteger,cinteger,pricenumeric,nametext,constraintproduct_no_pkeyprimarykey(product_no)
);

上面的product_no_pkey是一个别名。

2.字段约束

createtableproduct(
product_nointegerprimarykey,cinteger
pricenumeric,nametext
)

字段约束的创建是在你需要创建为主键的字段后面加上primary key就可以了,同样的你也可以给他起一个别名

createtableproduct(
product_nointegerconstrainttest_keyprimarykey,--test_key在这里就是一个别名
binteger,nametext
)

在官方文档上面有一句话:

Technically,a primary key constraint is simply a combination of a unique constraint and a not-null constraint.

翻译:从技术上来说, 主键就是唯一约束与非空约束的组合

createtableproduct3(
product_nointegeruniquenotnull,nametext
)
createtableproduct3(
product_nointegerprimarykey,nametext
)

上面两个是等价的。

但是一个表里面只能拥有一个主键。

createtableproduct3(
product_nointegeruniquenotnull,bintegeruniquenotnull,bintegerprimarykey,255);">就好比是上的两个例子一样,第二例子是不能通过。
会提示错误:

ERROR: multiple primary keys for table "product3" are not allowed

SQL 状态: 42P16

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读