使用PostgreSQL中的where ANSI join语法更新所有行

使用PostgreSQL中的where ANSI join语法更新所有行,sql,postgresql,join,Sql,Postgresql,Join,我正在尝试对where子句中的联接进行更新。我知道PostgreSQL有一个from子句,我可以用它来处理隐式连接,如下所示: update tbl1 t1 set name = 'foo' from tbl2 t2 where t2.id = t1.table2_id and t2.region = 'bar' update tbl1 set name = 'foo' from tbl1 t1 inner join tbl2 t2 on t2.id = t1.table2_id whe

我正在尝试对where子句中的联接进行更新。我知道PostgreSQL有一个from子句,我可以用它来处理隐式连接,如下所示:

update tbl1 t1 set name = 'foo'
from tbl2 t2
where t2.id = t1.table2_id
and t2.region = 'bar'
update tbl1 set name = 'foo' 
from tbl1 t1 
inner join tbl2 t2 on t2.id = t1.table2_id 
where t2.region = 'bar'
但是,我有生成ANSI连接而不是隐式连接的现有代码。环顾堆栈溢出,我读到我可以这样做:

update tbl1 t1 set name = 'foo'
from tbl2 t2
where t2.id = t1.table2_id
and t2.region = 'bar'
update tbl1 set name = 'foo' 
from tbl1 t1 
inner join tbl2 t2 on t2.id = t1.table2_id 
where t2.region = 'bar'
不幸的是,这似乎不起作用,它不是只更新2行,而是更新所有行,而不管from/where子句中有什么


我遗漏了什么?

是的,这是一个副作用,是由于它将
t1
视为与正在更新的表不同的表。有两种方法可以解决这个问题

  • 使用发布到
    UPDATE
    的第一个查询

  • 向第二个查询添加一个条件,如
    tbl1.id=t1.id
    ,以便强制更新表的1到1映射