更改要链接到另一个表的序列

时间:2017-05-11 06:53:55

标签: sql postgresql sequence alter postgresql-9.5

所以我通过Python后端通过HTTP将大约150,000行数据上传到数据库中,并且上传需要一段时间,因此我将其插入到新表中,然后我将其与旧表交换(通过重命名)表:

create table tmp (like main);
alter sequence main_id_seq restart;
alter table tmp alter column id set default nextval('main_id_seq');
drop table main cascade;  -- THIS REMOVES THE SEQUENCE ^^^^^^^
alter table tmp rename to main;

如何将序列更改为不链接到main表,这样当我删除main表时,序列将保持与当前tmp表的链接(新的main)?

2 个答案:

答案 0 :(得分:1)

你可以通过使专栏"拥有"序列

alter sequence main_id_seq
  owned by main.id;

答案 1 :(得分:1)

use改变序列:

t=# create table s120(i bigserial);
CREATE TABLE
t=# \d+ s120;
                                            Table "public.s120"
 Column |  Type  |                    Modifiers                     | Storage | Stats target | Description
--------+--------+--------------------------------------------------+---------+--------------+-------------
 i      | bigint | not null default nextval('s120_i_seq'::regclass) | plain   |              |

t=# create table s121(i bigint);
CREATE TABLE
t=# alter sequence s120_i_seq owned by s121.i;
ALTER SEQUENCE
t=# drop table s120;
DROP TABLE
t=# alter table s121 alter COLUMN i set default nextval('s120_i_seq'::regclass);
ALTER TABLE
t=# \d+ s121
                                       Table "public.s121"
 Column |  Type  |                Modifiers                | Storage | Stats target | Description
--------+--------+-----------------------------------------+---------+--------------+-------------
 i      | bigint | default nextval('s120_i_seq'::regclass) | plain   |              |