Postgresql序列与串行

Se *_*ong 18 sql postgresql

我想知道何时选择序列更好,何时使用串口更好.

我想要的是在插入后使用返回最后一个值

SELECT LASTVAL();
Run Code Online (Sandbox Code Playgroud)

我读了这个问题 PostgreSQL Autoincrement

我从来没有使用过串口.

zed*_*xus 29

查看关于序列与序列的好答案

序列将只创建唯一数字序列.它不是数据类型.这是一个序列.例如:

create sequence testing1;
select nextval('testing1');  -- 1
select nextval('testing1');  -- 2
Run Code Online (Sandbox Code Playgroud)

你可以在多个地方使用相同的序列,如下所示:

create sequence testing1;
create table table1(id int not null default nextval('testing1'), firstname varchar(20));
create table table2(id int not null default nextval('testing1'), firstname varchar(20));

insert into table1 (firstname) values ('tom'), ('henry');
insert into table2 (firstname) values ('tom'), ('henry');

select * from table1;

| id | firstname |
|----|-----------|
|  1 |       tom |
|  2 |     henry |

select * from table2;

| id | firstname |
|----|-----------|
|  3 |       tom |
|  4 |     henry |
Run Code Online (Sandbox Code Playgroud)

Serial是一种伪数据类型.它将创建序列对象.让我们来看一个直截了当的表(类似于你将在链接中看到的表).

create table test(field1 serial);
Run Code Online (Sandbox Code Playgroud)

这将导致序列与表一起创建.序列名称的命名法是__seq.以上内容相当于:

create sequence test_field1_seq;
create table test(field1 int not null default nextval('test_field1_seq'));
Run Code Online (Sandbox Code Playgroud)

另见:http://www.postgresql.org/docs/9.3/static/datatype-numeric.html

您可以重用串行数据类型自动创建的序列,也可以选择每个表使用一个序列/序列.

create table table3(id serial, firstname varchar(20));
create table table4(id int not null default nextval('table3_id_seq'), firstname varchar(20));
Run Code Online (Sandbox Code Playgroud)

(这里的风险是,如果删除table3并继续使用table3的序列,我们将收到错误)

create table table5(id serial, firstname varchar(20));    
insert into table3 (firstname) values ('tom'), ('henry');
insert into table4 (firstname) values ('tom'), ('henry');
insert into table5 (firstname) values ('tom'), ('henry');

select * from table3;
| id | firstname |
|----|-----------|
|  1 |       tom |
|  2 |     henry |

select * from table4; -- this uses sequence created in table3
| id | firstname |
|----|-----------|
|  3 |       tom |
|  4 |     henry |

select * from table5;
| id | firstname |
|----|-----------|
|  1 |       tom |
|  2 |     henry |    
Run Code Online (Sandbox Code Playgroud)

请随意尝试一个示例:http://sqlfiddle.com/#!15/074ac/1

  • 是的,但是`serial`不是实际的数据类型,它是伪数据类型 - 这是一个重要的区别:http://stackoverflow.com/a/27309311/939860或http://stackoverflow.com/a/14651788/939860只有在特殊情况下共享一个序列才有意义,在这种情况下你会使用一个独立的序列,而不是一个串行列的"拥有"序列 - 从而避免你提到的警告答案的底部. (6认同)

rap*_*2-h 12

2021年答案使用identity

我想知道什么时候选择序列比较好,什么时候使用串行比较好。

不是整个问题的答案(仅是上面引用的部分),我仍然认为它可以帮助更多的读者。您不应该使用序列或串行,您应该更喜欢使用identity列:

create table apps (
    id integer primary key generated always as identity
);
Run Code Online (Sandbox Code Playgroud)

请参阅此详细答案:/sf/answers/3871051901/(以及https://wiki.postgresql.org/wiki/Don%27t_Do_This#Don.27t_use_serial