On Tue, 1 Apr 2008, "John Reeve" <jreeve@pelagodesign.com> writes:
> I have the following scenario:
>
> A 'task' table that has the fields:
> id => primary key, updated on each insert using a sequence
> customerid => integer
> localid => integer
>
> I need the localid to be sequential and unique per unique customerid. The data needs to look like this:
> 1, 92, 1
> 2, 92, 2
> 3, 93, 1
> 4, 93, 2
> 5, 93, 3
> 6, 92, 3
> and so on
>
> I am presently doing this on the INSERT using an INNER SELECT, like this:
>
> INSERT INTO task (id, customerid, localid) VALUES (nextval('task_id'),
> 92, (SELECT MAX(localid) + 1 FROM task WHERE customerid = 92));
Why not creating a separate serial for localid field? It won't
contradict with your making localid to be sequential and unique per
unique customerid restriction.
CREATE TABLE task ( id serial PRIMARY KEY, customerid integer, localid serial
);
CREATE UNIQUE INDEX task_customerid_localid_idx ON task (customerid, localid);
INSERT INTO task (customerid) VALUES (92);
If I didn't get you wrong, this should solve your problem.
Regards.