Thread: Value specific sequences?

Value specific sequences?

From
"Dmitri Bichko"
Date:
Hello everyone,

I have a table of entities, each entity has a parent_id, I'd like to
have an insert trigger that assigns to that entity a sequential number
which gets incremented per parent_id.

i.e. doing:
INSERT INTO foo(id, parent_id) VALUES('a',1);
INSERT INTO foo(id, parent_id) VALUES('b',1);
INSERT INTO foo(id, parent_id) VALUES('c',2);

Should result in 'foo' containing:
id    parent_id    parent_index'a'    1    0'b'    1    1'c'    2    0

The two ways that come to mind are quering 'foo' on every insert for the
largest index for that parent_id (which seems slow) and using a separate
table of counters (which seems breaky).

Performance wise: the number of rows in 'foo' is not limited (ie will
grow continuously over the life of the app), but each parent_id will
usually only have about 10 foo's associated with it.  To make things
simple, nothing can be deleted from foo, and once inserted the relevant
values cannot change.

Is there an elegant way to do this?

Your help greatly appreciated,
Dmitri