如何为每批新插入的行使用新的序列号?

use*_*256 2 sql postgresql sequence

是否可以对一批行使用序列,而不是在每次插入时获取新的 ID?我正在跟踪一组详细信息,并且我希望该序列适用于该组,而不是每个单独的行。所以我的数据应该是这样的:

id batch_id name  dept
1    99     John  Engineering
2    99     Amy   Humanities
3    99     Bill  Science
4    99     Jack  English
Run Code Online (Sandbox Code Playgroud)

这是batch_id我希望 Postgres 作为序列发出的。这可能吗?

Abe*_*sto 5

将batch_id定义为并在插入批量行之前手动batch_id bigint not null default currval('seqname')调用。nextval('seqname')

或者,对于完全自动化:

1) 为批次 ID 创建序列:

create sequence mytable_batch_id;
Run Code Online (Sandbox Code Playgroud)

2)创建表,声明batch id字段如下:

create table mytable (
    id bigserial not null primary key,
    batch_id bigint not null default currval('mytable_batch_id'),
    name text not null);
Run Code Online (Sandbox Code Playgroud)

3) 创建语句级触发器以递增批次 ID 序列:

create function tgf_mytable_batch_id() returns trigger language plpgsql
as $$
begin
    perform nextval('mytable_batch_id');
    return null;
end $$;

create trigger tg_mytablebatch_id
before insert on mytable
for each statement execute procedure tgf_mytable_batch_id();
Run Code Online (Sandbox Code Playgroud)

现在,当您将数据插入表中时,每个语句都将被解释为下一个批次。

例子:

postgres=# insert into mytable (name) values('John'), ('Amy'), ('Bill');
INSERT 0 3
postgres=# insert into mytable (name) values('Jack');
INSERT 0 1
postgres=# insert into mytable (name) values('Jimmmy'), ('Abigail');
INSERT 0 2
postgres=# table mytable;
 id | batch_id |    name     
----+----------+-------------
  1 |        1 | John
  2 |        1 | Amy
  3 |        1 | Bill
  4 |        2 | Jack
  5 |        3 | Jimmy
  6 |        3 | Abigail
(6 rows)
Run Code Online (Sandbox Code Playgroud)