I'm a bit new to SQL and having some trouble coming up with this query. I have two tables, a parent policies
table, and a child policies_sub
table which references the parent table via a policy_id
foreign key:policies
table:
| policy_id | col_to_update |
| ------------ | ------------ |
| 1 | 0 |
| 2 | 0 |policies_sub
table:
| policy_id | factor_enum |
| ------------ | ------------ |
| 1 | 1 |
| 2 | 0 |
I'd like to add the new column col_to_update
and set its default value based on whether there exists a row in policies_sub
with the same policy_id
and a value set for factor_enum
. For example, for policy_id=1
, since there is a row in policies_sub
for that policy_id
and a value set for factor_enum
, I want to then default the col_to_update
for that policy_id
to 1
. Hopefully that makes sense. I think this involves a JOIN clause but I'm unsure of how everything is supposed to come together.
1条答案
按热度按时间oalqel3c1#
One-time update:
On-the-fly actualization:
and the same triggers AFTER DELETE (use OLD.policy_id) and AFTER UPDATE (use both - i.e. 2 UPDATEs).
After triggers creation run one-time UPDATE once for current values actualization.