如何基于一个表与另一个数据库中的同一表更新数据库中的表记录?

问题描述

让我们假设我有两个数据库db1db2。我想执行类似的命令

update db2.person p2
set p2.name = p1.name
from db1.person p1
where p1.id = p2.id;

这在MysqL中是可能的,没有任何问题。我很难在Postgresql中实现它。

我尝试过的事情:

create extension postgres_fdw;

create server theservername
foreign data wrapper postgres_fdw
options(host 'localhost',dbname 'thedbname',port '5432');

create user mapping for theuser
server theservername
options(user 'theusername',password 'thepassword');

在这里我被困住了,我不知道该如何进行。这些麻烦在MysqL中都不存在。如何在Postgresql中克服它们?

解决方法

步骤如下:

步骤-1:创建扩展程序

create extension postgres_fdw;

步骤-2:创建服务器

create server theservername
foreign data wrapper postgres_fdw
options(host 'localhost',dbname 'thedbname',port '5432');

步骤-3:为服务器创建外部用户映射

create user mapping for theuser
server theservername
options(user 'theusername',password 'thepassword');

第4步:创建与另一个DB具有相同结构的外部表

create foreign table "schema_name"."local_table_name"
(
id_ int;
...
-- field list same as foreign table in other db
)
server theservername
options(SCHEMA_NAME 'foreign_schema',TABLE_NAME 'foreign_name');

现在,您可以像本地表一样在查询中使用local_table_name。它将对远程数据库执行所有操作。

您的更新查询可以这样写:

update local_table_name p2
set name = p1.name
from person p1
where p1.id = p2.id;