Postgresql使用update

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


解决问题

通过多张关联表更新主表的字段,根据状态更新为不同的值。


一、关联表更新

1.关联一张表

更新 table1 表中 num 字段的值为 table2 表中的 sum 的值

update table1 a
set a.num = b.sum
from table2 b
where a.id = b.rel_id and b.type = '1';

2.关联多张表

更新 table1 表中 num 字段的值为 table2 和 table3 表中的 sum 字段的和

update table1 a
set a.num = b.sum + c.sum
from table2 b
left join table3 c on b.id = c.rel_id
where a.id = b.rel_id and c.type = '1';
update table1 a
set a.num = b.sum + c.sum
from table2 b, table3 c
where a.id = b.rel_id and b.id = c.rel_id and c.type = '1';

二、根据状态更新为不同的值

根据 table2 表中的 type 的值,更新 table1 表中 num 字段的值

update table1 a
set a.num = case when b.type = '1' then b.sum else b.sum + 1 end
from table2 b
where a.id = b.rel_id;

根据 table3 表中的 type 的值,更新 table1 表中 num 字段的值为 table2 表中的值

update table1 a
set a.num = case when c.type = '1' then b.interest_sum else b.interest_sum + 1 end
from (
	select sum(interest) as interest_sum from table2 group by country
	) b
left join table3 c on b.rel_id = c.id
where a.rel_id = b.id and a.type = '1';

相关推荐

  1. Postgresql使用update

    2024-02-01 22:14:01       30 阅读
  2. python如何使用update

    2024-02-01 22:14:01       38 阅读
  3. electron-updater使用整理

    2024-02-01 22:14:01       41 阅读
  4. Docker使用2-Update the application

    2024-02-01 22:14:01       48 阅读
  5. postgresql的基本使用

    2024-02-01 22:14:01       35 阅读
  6. PostgreSql 索引使用技巧

    2024-02-01 22:14:01       39 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-01 22:14:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-01 22:14:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-01 22:14:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-01 22:14:01       20 阅读

热门阅读

  1. 学习python第三天

    2024-02-01 22:14:01       29 阅读
  2. k8s学习-Health Check

    2024-02-01 22:14:01       32 阅读
  3. 网课:校门外的树——牛客(题解)

    2024-02-01 22:14:01       40 阅读
  4. Spring相关框架中的bean及其实例化

    2024-02-01 22:14:01       31 阅读
  5. Ubuntu 22.04开发板更新源报错404 Not Found

    2024-02-01 22:14:01       26 阅读
  6. XML详解

    XML详解

    2024-02-01 22:14:01      38 阅读
  7. 2024-01-31-好的技术文章汇总

    2024-02-01 22:14:01       33 阅读
  8. 【无标题】

    2024-02-01 22:14:01       34 阅读
  9. Unity_Visual Effect Graph

    2024-02-01 22:14:01       28 阅读