美文网首页
postgresql的update inner join

postgresql的update inner join

作者: nil_ddea | 来源:发表于2020-07-26 23:32 被阅读0次

在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性能

相关文章

网友评论

      本文标题:postgresql的update inner join

      本文链接:https://www.haomeiwen.com/subject/tchnlktx.html