PostgreSQL INSERT FROM SELECT带有附加列

时间:2016-04-27 07:13:35

标签: sql postgresql sql-insert

我在数据库T1中有表DB1,在数据库T2中有表DB2,这些表与C_additional中的列T1几乎完全相同{1}},T2中不存在{1}}。我需要将所有行从T2转移到T1,为我插入的每一行设置一些C_additional值。例如:T1T2只有一列C1 integerT1也有C_additionaltext },所以我的代码看起来像这样:

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?

2 个答案:

答案 0 :(得分:1)

您可以在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) 

答案 1 :(得分:0)

你能试试吗?

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)