假设我有db1
和db2
两个数据库。我想执行类似的命令
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:使用与另一个数据库相同的结构创建外表
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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句