PostgreSQL
 SQL >> Base de Dados >  >> RDS >> PostgreSQL

Uma sequência do PostgreSQL que reinicia por outra coluna

Sem problema! Vamos construir duas tabelas — stuff, a que você descreve, e things, que ela referencia:

CREATE TABLE things ( id serial primary key, name text ); CREATE TABLE stuff ( id integer references things, seq integer NOT NULL, notes text, primary key (id, seq) );

Agora configure things com um trigger que cria uma nova sequência sempre que uma linha for adicionada:

CREATE FUNCTION make_thing_seq() RETURNS trigger LANGUAGE plpgsql AS $$ begin execute format('create sequence thing_seq_%s', NEW.id); return NEW; end $$; CREATE TRIGGER make_thing_seq AFTER INSERT ON things FOR EACH ROW EXECUTE PROCEDURE make_thing_seq();

Isso lhe dá thing_seq_1, thing_seq_2 e assim por diante. Depois, um segundo trigger em stuff escolhe a sequência certa a cada vez:

CREATE FUNCTION fill_in_stuff_seq() RETURNS trigger LANGUAGE plpgsql AS $$ begin NEW.seq := nextval('thing_seq_' || NEW.id); RETURN NEW; end $$; CREATE TRIGGER fill_in_stuff_seq BEFORE INSERT ON stuff FOR EACH ROW EXECUTE PROCEDURE fill_in_stuff_seq();

Agora cada linha que entra em stuff usa seu id para chamar nextval na sequência correspondente. Veja uma demonstração:

test=# insert into things (name) values ('Joe'); INSERT 0 1 test=# insert into things (name) values ('Bob'); INSERT 0 1 test=# select * from things; id | name ----+------ 1 | Joe 2 | Bob (2 rows) test=# insert into stuff (id, notes) values (1, 'Keychain'); INSERT 0 1 test=# insert into stuff (id, notes) values (1, 'Pet goat'); INSERT 0 1 test=# insert into stuff (id, notes) values (2, 'Family photo'); INSERT 0 1 test=# insert into stuff (id, notes) values (1, 'Redundant lawnmower'); INSERT 0 1 test=# select * from stuff; id | seq | notes ----+-----+--------------------- 1 | 1 | Keychain 1 | 2 | Pet goat 2 | 1 | Family photo 1 | 3 | Redundant lawnmower (4 rows)

Como você pode ver, cada id pai recebe seu próprio contador independente e sem lacunas.