2016-11-28 48 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:好点。我只是做了一部分的复制和粘贴。 –