This question is the continuation of this one.
I have the following table egr
:
+---------+---------+------------+
| egrid | offid | groupid |
+---------+---------+------------+
| 1000 | 1 | 101 |
| 1001 | 1 | 202 |
| 1002 | 2 | 202 |
| 1003 | 2 | 404 |
+---------+---------+------------+
Note that egrid
is a sequence.
I would like to insert missing groupids that the offid 2 does not have (compared to offid 1). Result would be:
+---------+---------+------------+
| egrid | offid | groupid |
+---------+---------+------------+
| 1000 | 1 | 101 |
| 1001 | 1 | 202 |
| 1002 | 2 | 202 |
| 1003 | 2 | 404 |
| 1004 | 2 | 101 | --> new row to insert
+---------+---------+------------+
My try below, based on the answer of my other question (not working). The problem I have is that the sequence is incremented with the select statement. But if there are 555 rows with offid = 1, it will be incremented 555 times although in the end, only a few will be inserted. I am looking for a nicer way to do it.
INSERT INTO egr (egrid, offid, groupid)
SELECT nextval('seq_egrid'), 2, groupid
FROM egr
WHERE offid = 1
EXCEPT
SELECT egrid, 2, groupid
FROM egr
WHERE offid = 2
ON CONFLICT DO NOTHING;