PostgreSQL-为非主键创建一个自动增量列

PostgreSQL-为非主键创建一个自动增量列

问题描述:

我使用的是与开源Parse Server集成的PostgreSQL 9.5 X64.我的表具有以下结构.

I am with PostgreSQL 9.5 X64 integrated with the open-source Parse Server. My table has the following structure.

objectId (text with fixed 10 characters),
item_id (integer),
item_name (text with various length)

由于使用了Parse Server,objectId是主键.它由Parse Server自动生成. item_id不是主键.我想在创建新记录时使item_id自动增加1.在创建表中如何实现?

The objectId is the primary key due to use of Parse Server. It is automatically generated by Parse Server. The item_id is not a primary key. I would like to have item_id automatically increment by 1 when a new record is created. How can this be achieved in Create Table?

您可以尝试将item_id列设置为SERIAL.我不知道是否可以更改当前的item_id列以使其为串行,因此我们可能必须删除该列,然后将其添加回去,如下所示:

You may try making the item_id column SERIAL. I don't know whether or not it's possible to alter the current item_id column to make it serial, so we might have to drop that column and then add it back, something like this:

ALTER TABLE yourTable DROP COLUMN item_id;
ALTER TABLE yourTable ADD COLUMN item_id SERIAL;

如果item_id列中已经有数据,那么从串行角度看可能没有意义,因此希望删除它不会有任何危害.

If there is data in the item_id column already, it may not make sense from a serial point of view, so hopefully there is no harm in deleting it.