简体   繁体   English

基于postgresql中where子句的动态插入/更新

[英]Dynamic Insert/update based on where clause in postgresql

I have two tables as shown below我有两个表,如下所示

ob_period ob_period

person_id     ob_start_date

  1            2007/02/11
  2            2008/05/13  
  3            2008/07/29
  4            2006/03/21

visit访问

person_id     visit_date

  1            2003/06/21
  2            2005/02/23  
  3            2006/04/19
  5            2004/06/11

I would like to update the "ob_start_date" of "ob_period" table with "visit_date" of visit_table我想用visit_table的“visit_date”更新“ob_period”表的“ob_start_date”

I was trying something like below for update but it can't work as I am not sure how to update with a dynamic value from another table我正在尝试类似下面的更新,但它无法工作,因为我不确定如何使用另一个表中的动态值进行更新

update ob_period a
set a.ob_start_date = b.visit_date
where a.person_id = b.person_id

I expect my output to be like as shown below我希望我的输出如下所示

output输出

person_id     visit_date

  1            2003/06/21
  2            2005/02/23  
  3            2006/04/19
  4            2006/03/21

Can you help me with this please?你能帮我解决这个问题吗?

You need a table reference to the second table:您需要对第二个表的表引用:

update ob_period p
    set ob_start_date = v.visit_date
    from visit v
    where p.person_id = v.person_id

Try this:尝试这个:

 update ob_period a
    set a.ob_start_date = b.visit_date
    from visit b
    where a.person_id = b.person_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM