2016-04-27 38 views
2

我在數據庫DB1和表T2T1在數據庫DB2,這些表具有除了C_additional柱幾乎相同的列集合中T1,其不存在於T2。我需要將T2中的所有行轉移到T1,爲插入的每一行設置一些值C_additional。例如:T1T2只有一個列integer類型的C1T1也有text類型的C_additional列,所以我的代碼如下所示:PostgreSQL的插入來自SELECT與附加列

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?

+0

顯示我們T1的和T2的定義。 – jarlh

+0

'C_additional ='needed_value'是一個布爾表達式,用於評估列名「C_additional」是否等於常量「needed_value」。如果你想要一個列別名使用一個:''needed_value'as c_additional' –

回答

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) 
+0

這一個爲我工作,謝謝。 – bnopne

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)