问题描述
SELECT
t.*
FROM "database" d,t,dblink_exec(
format('dbname = %s host = %s port = %s user = %s password = %s',databasename,servername,port,username,"password"),format('UPDATE
table1 a
SET
(col1,col2) = (SELECT
%L :: json,Now()
FROM t b -- t is the local table (from current db)
WHERE b.col2 = a.col2
AND b.col3 = a.col3
AND b.col4 = a.col4)
WHERE a.col2 = ''ABC''
AND a.col3 = ''DEF''
',data )) -- column data is from table ```t```
WHERE databasename = 'otherdb';
如何通过将本地表连接到其他数据库来更新记录。我需要将桌子 t
固定在正确的位置。我无法在其他数据库上运行它,因为还有其他依赖项(主要是时间)。
解决方法
我能够通过首先加入表并形成 UPDATE 语句并将 UPDATE 语句提供给 dblink_exec 来实现这一点。
SELECT
dblink_exec(
format('dbname = %s host = %s port = %s user = %s password = %s',databasename,servername,port,username,"password"),format ('UPDATE table1 %1$sSET col4 = %3$L :: json,%2$scol3 = now() %1$sWHERE col3 = %4$L %2$sAND col3 = ''ABC'' %2$sAND col2 = ''DEF'';',E'\n',E'\n\t',t.data,t.col3
)
)
FROM t
INNER JOIN
(
SELECT x.*
FROM "database" d,dblink(
format('dbname = %s host = %s port = %s user = %s password = %s',"password"
),'SELECT
*
FROM table1
WHERE col1 = ''ABC''
AND col2 = ''DEF''
'
) AS x( col1 TEXT,col2 TEXT,col3 TEXT,col4 TEXT
)
WHERE databasename = 'otherdb'
) as otherdb
CROSS JOIN "database" d
ON otherdb.col1 = t.col1
AND otherdb.col2 = t.col2
AND otherdb.col1 = 'DEF'
AND otherdb.col2 = 'ABC'
WHERE databasename = 'otherdb';