PostgreSQL 主键 id 数据类型从串行到大串行?

use*_*690 6 postgresql

我做了一些研究,但找不到我要寻找的确切答案。目前我有一个主键列“id”,它设置为串行,但我想将其更改为 bigserial 以映射到 Java 层中的 Long。考虑到这是一个现有的表,实现这一目标的最佳方法是什么?我认为我的 Postgres 版本是 10.5。我也知道 serial 和 bigserial 都不是数据类型。

kli*_*lin 20

Postgres 9.6或更早版本中,由serial列创建的序列已经返回bigint. 您可以使用psql进行检查:

drop table if exists my_table;
create table my_table(id serial primary key, str text);

\d my_table

                            Table "public.my_table"
 Column |  Type   | Collation | Nullable |               Default                
--------+---------+-----------+----------+--------------------------------------
 id     | integer |           | not null | nextval('my_table_id_seq'::regclass)
 str    | text    |           |          | 
Indexes:
    "my_table_pkey" PRIMARY KEY, btree (id)


\d my_table_id_seq

                      Sequence "public.my_table_id_seq"
  Type  | Start | Minimum |       Maximum       | Increment | Cycles? | Cache 
--------+-------+---------+---------------------+-----------+---------+-------
 bigint |     1 |       1 | 9223372036854775807 |         1 | no      |     1
Owned by: public.my_table.id
Run Code Online (Sandbox Code Playgroud)

所以你应该只改变串行列的类型:

alter table my_table alter id type bigint;
Run Code Online (Sandbox Code Playgroud)

该行为已经改变了Postgres的10

此外,为 SERIAL 列创建的序列现在生成 32 位宽的正值,而以前的版本生成 64 位宽的值。如果值仅存储在列中,则这没有明显影响。

因此在 Postgres 10+ 中:

alter sequence my_table_id_seq as bigint;
alter table my_table alter id type bigint;
Run Code Online (Sandbox Code Playgroud)

  • 嗨,我尝试在 postgresql 10.5 中创建一个串行主键。`public.my_table_id_seq` 实际上有 `integer` 类型而不是 `bigint` 类型。在最近的 postgresql 版本中,串行功能是否以某种方式发生了变化?干杯。 (2认同)