2016-11-28 49 views
0

我有以下三個表,每列有兩列。PostgreSQL 9.5:與CTE衝突更新

:CT1

create table ct1 
(
id int primary key, 
name varchar(10) 
); 

:CT2

create table ct2 
(
id int primary key, 
name varchar(10) 
); 

:CT3

create table ct3 
(
id int primary key, 
name varchar(10) 
); 

插入

insert into ct1 values(1,'A'); 
insert into ct1 values(2,'B'); 

insert into ct1 values(11,'C'); 
insert into ct1 values(12,'D'); 

注意:我想插入選項卡表CT3記錄由另外兩個表的使用CTE(強制)選擇數據。

我嘗試:

查詢

INSERT INTO ct3(id,name) 
WITH CTE 
AS 
(
    SELECT id,name from ct1 
    WHERE id is not null 
), 
cte2 
as 
(
    SELECT id,name from ct2 
    WHERE name is not null 
) 
select c1.id as id1,c2.name as name1 from cte as c1,cte2 as c2 
on conflict (id) do update 
set 
id = id1, 
name = name1; 

錯誤

ERROR: column "id1" does not exist 
LINE 17: id = id1, 
+0

'從cte作爲c1,cte2作爲c2'看起來不正確。你真的**想在兩張桌子之間交叉**加入(笛卡爾產品)嗎? –

回答

0

插入需要後成爲最終的查詢的CTE

WITH CTE 
AS 
(
    SELECT id,name from ct1 
    WHERE id is not null 
), 
cte2 
as 
(
    SELECT id,name from ct2 
    WHERE name is not null 
) 
INSERT INTO ct3(id,name) --<< INSERT needs to go here 
select c1.id as id1,c2.name as name1 
from cte as c1, 
    cte2 as c2 --<< are you SURE you want a cross join here? 
on conflict (id) do update 
-- no need to update the ID column here as that is the one used for conflict detection 
set name = name1; 
+1

衝突更新使用相同的值將插入(我不質疑你的語法)的重點是什麼? –

+0

@TimBiegeleisen:好點。我只是做了一部分的複製和粘貼。 –