2011-08-01 77 views
61

我想從另一個表插入數據到一個表,並且這些表只有一列是共同的。問題是,TABLE1有不接受空值的列,所以我不能讓它們爲空,我無法從TABLE2中獲取它們。PostgreSQL:插入從另一個表

我有表1: ID,COL_1(NOT NULL),COL_2(NOT NULL),col_3(NOT NULL)

和TABLE2: ID,爲col_a,col_b,col_c

怎麼可能我將TABLE2中的id插入到TABLE1中,並用「data1」,「data2」,「data3」等硬編碼字符串填充col_1-3?

INSERT INTO TABLE1 (id) SELECT id FROM TABLE2 WHERE col_a = "something"; 

將導致:

ERROR: null value in column "col_1" violates not-null constraint

回答

128

只需在SELECT提供文字值:

INSERT INTO TABLE1 (id, col_1, col_2, col_3) 
SELECT id, 'data1', 'data2', 'data3' 
FROM TABLE2 
WHERE col_a = 'something'; 

選擇列表中可以包含any value expression

But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

和一個字符串文字當然是一種價值表達。

4

你可以使用COALESCE:

insert into destination select coalesce(field1,'somedata'),... from source;