PostgreSQL主键ID数据类型是从串行到bigserial?

时间:2018-09-06 01:35:19

标签: postgresql

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

1 个答案:

答案 0 :(得分:3)

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

因此,您只应更改序列列的类型:

alter table my_table alter id type bigint;

Postgres 10 中的行为has changed

  

此外,为SERIAL列创建的序列现在生成正32位宽的值,而以前的版本生成64位宽的值。如果这些值仅存储在列中,则不会产生可见效果。

在Postgres 10+中的作用:

alter sequence my_table_id_seq as bigint;
alter table my_table alter id type bigint;