postgresql的update inner join

在mysql中遇到依赖表a的数据来大量更新表b的数据时可以使用update join的语法
在postgresql也可以做到 语法和mysql有一些差别

这是postgresql的update语法

[ WITH [ RECURSIVE ] with_query [, ...] ]
UPDATE [ ONLY ] table [ [ AS ] alias ]
    SET { column = { expression | DEFAULT } |
          ( column [, ...] ) = ( { expression | DEFAULT } [, ...] ) } [, ...]
    [ FROM from_list ]
    [ WHERE condition | WHERE CURRENT OF cursor_name ]
    [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]

update中可以包含一个form子句 当包含form子句时 where子句中需要指明update的表和form子句的关联关系
例如:
employee:id name attendance_duration ...
attendance: employee_id duration date ...
将全部员工上月的出勤时间累加到employee表的attendance_duration中
update employee set attendance_duration=attendance_duration+t.ad
from (select sum(duration) from attendance where date<... and date >... group by employee_id) as t
where employee.id =attendance.employee_id

利用这个特性配合case when等语法实现复杂业务逻辑 可以避免大量数据逐一更新
能极大提高update性能

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容