简体   繁体   English

最好使用 SERIAL PRIMARY KEY 或 GENERATED ALWAYS AS IDENTITY 作为 PostgreSQL 中的主键

[英]Better to use SERIAL PRIMARY KEY or GENERATED ALWAYS AS IDENTITY for primary key in PostgreSQL

Not sure which option is latest best practice?不确定哪个选项是最新的最佳实践? I read on on this tutorial that:我在本教程中读到:

https://www.postgresqltutorial.com/postgresql-identity-column/ https://www.postgresqltutorial.com/postgresql-identity-column/

PostgreSQL version 10 introduced a new constraint GENERATED AS IDENTITY that allows you to automatically assign a unique number to a column. PostgreSQL 版本 10 引入了一个新的约束 GENERATED AS IDENTITY,它允许您自动为列分配一个唯一编号。

The GENERATED AS IDENTITY constraint is the SQL standard-conforming variant of the good old SERIAL column. GENERATED AS IDENTITY 约束是良好的旧 SERIAL 列的 SQL 符合标准的变体。

In the example they use the identity as the primary key:在示例中,他们使用身份作为主键:

CREATE TABLE color (
    color_id INT GENERATED ALWAYS AS IDENTITY,
    color_name VARCHAR NOT NULL
);

When you reference this table for a FOREIGN KEY as per the below:当您按照以下方式为 FOREIGN KEY 引用此表时:

CREATE TABLE pallet (
    id INT GENERATED ALWAYS AS IDENTITY,
    color_1 REFERENCES color
    color_2 REFERENCES color
);

Will it know that the identity is the primary key now?:它会知道身份现在是主键吗?:

Will it know that the identity is the primary key now?它会知道身份现在是主键吗?

No (and neither would a serial do that).不( serial也不会那样做)。

You need to define the primary key explicitly:您需要明确定义主键:

CREATE TABLE color (
    color_id INT  primary key GENERATED ALWAYS AS IDENTITY,
    color_name VARCHAR NOT NULL
);

Not sure which option is latest best practice?不确定哪个选项是最新的最佳实践?

It's recommended to use identity instead of serial .建议使用identity而不是serial

Quote from the Postgres Wiki 引用自 Postgres Wiki

For new applications, identity columns should be used instead.对于新的应用程序,应该改用标识列。

Why not serial?为什么不连续?
The serial types have some weird behaviors that make schema, dependency, and permission management unnecessarily cumbersome.串行类型有一些奇怪的行为,使模式、依赖和权限管理变得不必要的麻烦。

Finally, identity columns conform with the SQL standard, while serial is PostgreSQL dialect.最后,identity 列符合 SQL 标准,而serial是 PostgreSQL 方言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM