根据另一列的更改来更改一列的值

时间:2018-10-02 08:44:58

标签: sql postgresql

假设我有一个这样的SQL表:

+----+------+-------+
| id | ColA | ColB  |
+----+------+-------+
|  1 | red  | false |
+----+------+-------+

当我将colB的值设置为'true'时,我希望colA的值更改为'blue',所以我最终得到:

+----+------+------+
| id | ColA | ColB |
+----+------+------+
|  1 | blue | true |
+----+------+------+

我意识到我可以同时更新两个列,但是我想知道是否可以在数据库中添加自动执行此操作的规则。

我正在使用psql 10.4。

2 个答案:

答案 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:

  1. Define a trigger that updates ColA when ColB is updated.

  2. Define a view on top of original table that computes ColA.

  3. Forget having ColA in database and compute the value in SELECT.

相关问题