如何在PostgreSQL中设置自动增量主键?

我在PostgreSQL中有一个有22列的表,我想添加一个自动递增的主键。

我试图创建一个名为`id'的BIGSERIAL类型的列,但pgadmin回应了一个错误。

ERROR: sequence must have same owner as table it is linked to.

有人知道如何解决这个问题吗? 如何在PostgreSQL中添加创建一个自动递增的主键,而不重新创建表?

解决办法

试试这个命令。

ALTER TABLE your_table ADD COLUMN key_column BIGSERIAL PRIMARY KEY;

用与你创建表的用户相同的DB用户试试。

评论(11)

postgresql中自动递增主键。

第1步,创建你的表:

CREATE TABLE epictable
(
    mytable_key    serial primary key,
    moobars        VARCHAR(40) not null,
    foobars        DATE
);

**第2步,像这样向你的表插入数值,注意在第一个参数列表中没有指定mytable_key,这导致默认序列自动递增。

insert into epictable(moobars,foobars) values('delicious moobars','2012-05-01')
insert into epictable(moobars,foobars) values('worldwide interblag','2012-05-02')

*第3步,从你的表中选择:**

el@voyager$ psql -U pgadmin -d kurz_prod -c "select * from epictable"

第4步,解释输出:

mytable_key  |        moobars        |  foobars   
-------------+-----------------------+------------
           1 | delicious moobars     | 2012-05-01
           2 | world wide interblags | 2012-05-02
(2 rows)

观察到mytable_key列已经自动递增。

建议:

你应该总是在你的表中使用一个主键,因为postgresql内部使用哈希表结构来提高插入、删除、更新和选择的速度。 如果有一个主键列(强制唯一且非空),可以依靠它来为哈希函数提供一个唯一的种子。 如果没有主键列,哈希函数就会变得低效,因为它选择了其他一些列作为键。

评论(3)

在postgresql中创建一个自动递增的主键,使用一个自定义序列:

第1步,创建你的序列:

create sequence splog_adfarm_seq
    start 1
    increment 1
    NO MAXVALUE
    CACHE 1;
ALTER TABLE fact_stock_data_detail_seq
OWNER TO pgadmin;

第2步,创建您的表格

CREATE TABLE splog_adfarm
(
    splog_key    INT unique not null,
    splog_value  VARCHAR(100) not null
);

第3步,插入到您的表格中

insert into splog_adfarm values (
    nextval('splog_adfarm_seq'), 
    'Is your family tree a directed acyclic graph?'
);

insert into splog_adfarm values (
    nextval('splog_adfarm_seq'), 
    'Will the smart cookies catch the crumb?  Find out now!'
);

第4步,观察行数

el@defiant ~ $ psql -U pgadmin -d kurz_prod -c "select * from splog_adfarm"

splog_key |                            splog_value                             
----------+--------------------------------------------------------------------
        1 | Is your family tree a directed acyclic graph?
        2 | Will the smart cookies catch the crumb?  Find out now!
(3 rows)

这两行的键从1开始,以1递增,这是由序列定义的。

奖励的精英专业提示:

程序员讨厌打字,打出nextval('splog_adfarm_seq')是很烦人的。 你可以为该参数输入DEFAULT来代替,像这样。

insert into splog_adfarm values (
    DEFAULT, 
    'Sufficient intelligence to outwit a thimble.'
);

为了让上面的方法奏效,你必须为splog_adfarm表的那个键列定义一个默认值。 哪个更漂亮。

评论(2)