我有很多带有自动增量PK的表,对于其中的大多数pg_get_serial_sequence
返回(正如我期望的那样)自动增量后面的序列名称,即SERIAL PK。但是对于一个表pg_get_serial_sequence
仅返回一个空字符串?
现在...我为这些表生成了CREATE脚本,但是我看不出这些表的创建脚本({{1}可以正常运行,而pg_get_serial_sequence
可以正常运行的表)之间没有任何原理上的区别工作正常,即返回空字符串)。
两个都有一些序列支持的SERIAL PK列。因此,情况似乎与我相同。但是,对于我的表之一,pg_get_serial_sequence
没有返回该后备序列的名称,它仅返回空字符串。
此特定表可能丢失什么?
是否需要做一些特殊的事情才能将给定序列设置为SERIAL序列?
如果没有,我应该找什么?我想念什么?
答案 0 :(得分:2)
这取决于表的创建方式。使用serial
时,序列会自动创建并与表关联:
create table my_table_auto(id serial);
select pg_get_serial_sequence('my_table_auto', 'id');
pg_get_serial_sequence
-----------------------------
public.my_table_auto_id_seq
(1 row)
手动创建序列时,该序列与表格无关:
create sequence my_sequence;
create table my_table_manually(id int default nextval('my_sequence'));
select pg_get_serial_sequence('my_table_manually', 'id');
pg_get_serial_sequence
------------------------
(1 row)
您可以更改序列以将其与表格关联:
alter sequence my_sequence owned by my_table_manually.id;
select pg_get_serial_sequence('my_table_manually', 'id');
pg_get_serial_sequence
------------------------
public.my_sequence
(1 row)
答案 1 :(得分:0)
您的这张表很有可能是通过like
子句创建的,即从表模板中创建的。
我经常使用表模板来分解一些常见的列,并且我发现,如果将主键包含在模板中,则所有衍生表仅使用一个序列生成器。
这有两个缺点:
pg_get_serial_sequence()
时,您会得到null
的结果。这里有一个完整的示例,其中table1
和table2
从名为template_basic
的表模板派生而来,其中包括id
和{{1}上的序列}是普通表。
table3
现在,如果您查看这三个表,您将看到drop table if exists table3 cascade;
drop table if exists table2 cascade;
drop table if exists table1 cascade;
drop table if exists template_basic cascade;
-- The template table
create table template_basic (
id serial,
title varchar,
created_dt timestamp,
primary key (id)
);
-- A table derived from template_basic
create table table1 (
like template_basic including all,
phone_number varchar,
city varchar,
country varchar
);
-- Another table derived from template_basic
create table table2 (
like template_basic including all,
first_name varchar,
family_name varchar
);
-- A normal table, but with an equivalent structure to table1 and table2
create table table3 (
id serial,
title varchar,
created_dt timestamp,
phone_number varchar,
city varchar,
country varchar,
primary key (id)
);
-- Populate
insert into table1 default values;
insert into table1 default values;
insert into table1 default values;
insert into table2 default values;
insert into table2 default values;
insert into table2 default values;
insert into table3 default values;
insert into table3 default values;
insert into table3 default values;
与table2.id
共享相同的顺序。另外,table1.id
有其自己的顺序。
table3.id
检索select id from table1;
id|
--|
1|
2|
3|
select id from table2;
id|
--|
4|
5|
6|
select id from table3;
id|
--|
1|
2|
3|
或table1.id
的序列名称时,您将得到一个table2.id
,如前所述。
null
要获取这两个表的顺序,必须调用模板表名称。
select pg_get_serial_sequence ('table1', 'id');
pg_get_serial_sequence|
----------------------|
|
select pg_get_serial_sequence ('table2', 'id');
pg_get_serial_sequence|
----------------------|
select pg_get_serial_sequence ('table3', 'id');
pg_get_serial_sequence|
----------------------|
public.table3_id_seq |