将主键int类型更改为serial

时间:2014-05-10 07:39:06

标签: postgresql primary-key auto-increment

有没有办法将现有的主键类型从int更改为serial而不删除表?我已经在表格中有很多数据,我不想删除它。

2 个答案:

答案 0 :(得分:38)

将int转换为串行more or less only means adding a sequence default to the value,以使其成为序列号;

  • 选择序列的起始值,大于表中的任何现有值 SELECT MAX(id)+1 FROM mytable

  • 为序列创建序列(tablename_columnname_seq是个好名字)
    CREATE SEQUENCE test_id_seq MINVALUE 3(假设您想从3开始)

  • 更改列的默认值以使用序列
    ALTER TABLE test ALTER id SET DEFAULT nextval('test_id_seq')

  • 更改表/列所拥有的序列;
    ALTER SEQUENCE test_id_seq OWNED BY test.id

A very simple SQLfiddle demo

和往常一样,养成在运行完整备份之前运行完整备份的习惯,改变来自互联网上随机人员的SQL查询; - )

答案 1 :(得分:-1)

-- temp schema for testing
-- ----------------------------
DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;

CREATE TABLE bagger
        ( id  INTEGER NOT NULL PRIMARY KEY
        , tralala varchar
        );

INSERT INTO bagger(id,tralala)
SELECT gs, 'zzz_' || gs::text
FROM generate_series(1,100) gs
        ;

DELETE FROM bagger WHERE random() <0.9;
-- SELECT * FROM bagger;

        -- CREATE A sequence and tie it to bagger.id
        -- -------------------------------------------
CREATE SEQUENCE bagger_id_seq;
ALTER TABLE bagger
        ALTER COLUMN id SET NOT NULL
        , ALTER COLUMN id SET DEFAULT nextval('player_id_seq')
        ;
ALTER SEQUENCE bagger_id_seq
        OWNED BY bagger.id
        ;
SELECT setval('bagger_id_seq', MAX(ba.id))
FROM bagger ba
        ;

     -- Check the result
     -- ------------------
SELECT * FROM bagger;

\d bagger
\d bagger_id_seq