postgresql 使用ctid更新表

cunj1qz1  于 2023-03-12  发布在  PostgreSQL
关注(0)|答案(2)|浏览(169)

我把t-sql代码翻译成PostgreSQL。我有临时表,我不能改变它的结构。这个表只有索引没有主键。在t-sql中更新这个表中的列我使用这个:

update t
set col_1 = tt.val
from table_1 t 
inner join table_2 tt on t.id = tt.t_id

但是在Postgres中我需要把我的临时表和他们自己连接起来进行更新,所以我可以使用ctid列来更新它(而不是PK)吗?或者这个方法有问题?我读到vacuum可以改变ctid

update table_1
set col_1 = tt.val
from table_1 t 
inner join table_2 tt on t.id = tt.t_id
where table_1.ctid = t.ctid
toiithl6

toiithl61#

用于从table_2获取id和valWITH cte,然后我们可以使用更新连接更新col1
您的第一个查询可以转换为如下内容:

with cte as (
  select t.id, tt.val
  from table_1 t 
  inner join table_2 tt on t.id = tt.t_id
)
update table_1 t
set col_1 = cte.val
from cte
where t.id = cte.id
ecbunoof

ecbunoof2#

您希望基于table_2中的数据更新table_1中的值。在Postgres中,您不应该在FROM子句中重复目标表。因此,原始的T-SQL UPDATE语句在Postgres中转换为以下内容:

update table_1
  set col_1 = tt.val
from table_2 tt 
where table_1.id = tt.t_id

相关问题