带有附加列的 PostgreSQL INSERT FROM SELECT
PostgreSQL INSERT FROM SELECT with additional column
我在数据库 DB1
中有 table T1
并且在数据库 DB2
中有 table T2
,那些 table具有几乎相同的列集,但 T1
中的 C_additional
列除外,T2
中不存在。我需要将所有行从 T2
转移到 T1
,为我插入的每一行设置一些值 C_additional
。例如:T1
和 T2
只有一列 C1
类型 integer
并且 T1
也有列 C_additional
类型 text
,所以我的代码如下所示:
INSERT INTO T1
SELECT
C1,
C_additional='needed_value'
FROM dblink(
'hostaddr=127.0.0.1 port=5432 dbname=DB2 user=postgres password=postgres',
'SELECT * FROM T2')
AS T2_row(C1 integer)
我收到以下错误:
ERROR: column "C_additional" does not exist
SQL state: 42703
Hint: There is a column named "C_additional" in table "T1", but it cannot be referenced from this part of the query.
如何使用 SQL 进行数据传输,还是应该使用 PG/SQL?
你能试试这个吗?
INSERT INTO T1
SELECT
C1,
'needed_value'
FROM dblink(
'hostaddr=127.0.0.1 port=5432 dbname=DB2 user=postgres password=postgres',
'SELECT * FROM T2')
AS T2_row(C1 integer)
您可以在 select
子句前用括号指定目标列:
INSERT INTO T1
(c1, c_additional) -- here
SELECT
C1,
'needed_value' -- just select a constant here
FROM dblink(
'hostaddr=127.0.0.1 port=5432 dbname=DB2 user=postgres password=postgres',
'SELECT * FROM T2')
AS T2_row(C1 integer)
我在数据库 DB1
中有 table T1
并且在数据库 DB2
中有 table T2
,那些 table具有几乎相同的列集,但 T1
中的 C_additional
列除外,T2
中不存在。我需要将所有行从 T2
转移到 T1
,为我插入的每一行设置一些值 C_additional
。例如:T1
和 T2
只有一列 C1
类型 integer
并且 T1
也有列 C_additional
类型 text
,所以我的代码如下所示:
INSERT INTO T1
SELECT
C1,
C_additional='needed_value'
FROM dblink(
'hostaddr=127.0.0.1 port=5432 dbname=DB2 user=postgres password=postgres',
'SELECT * FROM T2')
AS T2_row(C1 integer)
我收到以下错误:
ERROR: column "C_additional" does not exist
SQL state: 42703
Hint: There is a column named "C_additional" in table "T1", but it cannot be referenced from this part of the query.
如何使用 SQL 进行数据传输,还是应该使用 PG/SQL?
你能试试这个吗?
INSERT INTO T1
SELECT
C1,
'needed_value'
FROM dblink(
'hostaddr=127.0.0.1 port=5432 dbname=DB2 user=postgres password=postgres',
'SELECT * FROM T2')
AS T2_row(C1 integer)
您可以在 select
子句前用括号指定目标列:
INSERT INTO T1
(c1, c_additional) -- here
SELECT
C1,
'needed_value' -- just select a constant here
FROM dblink(
'hostaddr=127.0.0.1 port=5432 dbname=DB2 user=postgres password=postgres',
'SELECT * FROM T2')
AS T2_row(C1 integer)