PostgreSQL-为非主键创建一个自动增量列 [英] PostgreSQL - create an auto-increment column for non-primary key
问题描述
我使用的是与开源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.
这篇关于PostgreSQL-为非主键创建一个自动增量列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!