In our database we store policycase
records. A policycase has a 1:1 relation to a (requested) policy
record. The policy
record has a 1:n relationship to policy_map
. Where policy_map
is a key, value table.
When a policycase is changed from our user application, the complete policycase
record and all it's child records are copied and stored again. At least, that was the requirement. Due to a bug only a small number of the policy_map
records are copied to the new policycase
.
We want to execute an insert query that creates the missing policy_map
records for the copied record, when they do not exist.
The old policycase
can be recognized from a status HISTORICAL and the copied policycase
from a status ARCHIVED. Both policycase
s have the same uniqueid
field.
So the following select query gives me the policy_map
records for the historical and the archived (copied) policycase
records for a certain uniqueid
:
SELECT
policycase.status,
policy.id,
policy.uniqueid,
policy_map.map_key,
policy_map.map_value
FROM policycase
INNER JOIN policy ON policy.id = policycase.requested_id
INNER JOIN policy_map ON policy_map.policy_id = policy.id
WHERE policy.uniqueid = '91157235'
The result of this query is something like:
+------------+--------+----------+--------------------------------+-----------+
| status | id | uniqueid | map_key | map_value |
+------------+--------+----------+--------------------------------+-----------+
| HISTORICAL | 438957 | 91157235 | isPropertyOwner | TRUE |
| HISTORICAL | 438957 | 91157235 | livingAtProperty | TRUE |
| HISTORICAL | 438957 | 91157235 | stateOfMaintenance | GOED |
| HISTORICAL | 438957 | 91157235 | stateOfMaintenanceRoof | 0 |
| HISTORICAL | 438957 | 91157235 | unsecuredGuaranteeHouseContent | J |
| HISTORICAL | 438957 | 91157235 | unsecuredGuaranteeHouseFire | J |
| ARCHIVED | 451423 | 91157235 | isPropertyOwner | TRUE |
| ARCHIVED | 451423 | 91157235 | livingAtProperty | TRUE |
| ARCHIVED | 451423 | 91157235 | stateOfMaintenance | GOED |
+------------+--------+----------+--------------------------------+-----------+
In the table above, the map records
stateOfMaintenanceRoof
unsecuredGuaranteeHouseContent
unsecuredGuaranteeHouseFire
need to be copied to the policy_map
table, related to the ARCHIVED policycase
. That needs to be done for every uniqueid
in the database.
How would a query or function that accomplishes this look?
We are running Postgres 9.6
on Amazon RDS.
Best Answer
Setup:
Before insert:
The proposed INSERT:
NOTE: There may be a way to eliminate some of the joins but I'll leave it like this for now as it's easier (for me) to understand what's going oin.
After insert:
And here's a dbfiddle