假设我有一个这样的SQL表:
+----+------+-------+
| id | ColA | ColB |
+----+------+-------+
| 1 | red | false |
+----+------+-------+
当我将colB的值设置为'true'时,我希望colA的值更改为'blue',所以我最终得到:
+----+------+------+
| id | ColA | ColB |
+----+------+------+
| 1 | blue | true |
+----+------+------+
我意识到我可以同时更新两个列,但是我想知道是否可以在数据库中添加自动执行此操作的规则。
我正在使用psql 10.4。
答案 0 :(得分:1)
只是用例,因为您没有提到任何逻辑,所以假设您要用红色,然后用蓝色和真
select id, case when ColA='red' then 'blue' end as ColA,
case when ColA='red' then true end as ColB from t
答案 1 :(得分:1)
Since Postgresql 10 does not support computed columns, I think you have three options:
Define a trigger that updates ColA when ColB is updated.
Define a view on top of original table that computes ColA.
Forget having ColA in database and compute the value in SELECT.