Im trying to update a column (address_count)
on my people
table that must have the sum of records from another table (people_addresses)
plus some constraints.
The idea is that, the record on people
must exist on people_addresses
and must be present on at least one of the other tables (table a, table b)
SELECT pd.address_id, count (pd.person_id)
FROM person_addresses pd
WHERE EXISTS (SELECT a.person_id
FROM table_a a where a.person_id = pd.person_id)
OR EXISTS (SELECT b.person_id
FROM table_b b where b.person_id = pd.person_id)
GROUP BY pd.address_id
With the query above, I get the expected count, for each address that fits my requirements, altough, when I try to use it on a update, I get weird results, the records that don’t fit the requirements end up with wrong values on people_count
query im using:
UPDATE people d
SET people_count = (SELECT count (pd.person_id)
FROM person_addresses pd
WHERE EXISTS (SELECT a.person_id
FROM table_a a where a.person_id = pd.person_id)
OR EXISTS (SELECT b.person_id
FROM table_b b where b.person_id = pd.person_id)
AND d.id=pd.address_id
GROUP BY pd.address_id)
I get the correct result, on records that fit the requirements, but wrong values on the ones that dont fit, when I run the update.
Advertisement
Answer
The problem is in your conditions:
WHERE EXISTS ( ) OR EXISTS ( ) AND d.id = pd.adress_id
Is actually equivalent to:
WHERE EXISTS ( ) OR (EXISTS ( ) AND d.id = pd.adress_id)
You need to surround the OR
condition with parentheses to make your intent explicit:
WHERE (EXISTS ( ) OR EXISTS ( )) AND d.id = pd.adress_id
Also, the GROUP BY
clause is superfluous in the subquery. I would suggest removing it (you will get a 0
value if the subquery does not match).