我想要一个纯SQL查询来插入或更新多行。我开始工作一个,但只有一行:
WITH UPDATED_ITEMS as (
UPDATE table SET (columnC, columnD) = ($value3, $value4) WHERE id = $value5 returning *
)
INSERT INTO table (columnA, columnB, columnC, columnD) SELECT $value1, $value2, $value3, $value4 WHERE NOT EXISTS (SELECT * FROM updated_items)
现在我已经更改了更新条件,但是不知道如何使用insert进行更新:
WITH updated_items as (
UPDATE table as m SET
columnC = c.columnC
columnD = c.columnD
from (values ($value3, $value4, $value5), ($value8, $value9, $value10)
) as c(columnC, columnD, id)
where c.id::int4 = m.id returning *
)
INSERT INTO table (columnA, columnB, columnC, columnD)
SELECT ($value1, $value2, $value3, $value4, $value5), ($value6, $value7, $value8, $value9, $value10) WHERE NOT EXISTS (SELECT * FROM updated_items)
但是插入部分不起作用。有人请帮忙吗?
答案 0 :(得分:0)
我认为你基本上需要not exists
中的关联条款。您的更新引用了id
列,因此我也添加了该列。所以我认为这样做你想要的:
WITH updated_items as (
UPDATE table as m
SET columnC = c.columnC,
columnD = c.columnD
FROM (VALUES ($value3, $value4, $value5),
($value8, $value9, $value10)
) as c(columnC, columnD, id)
WHERE c.id::int4 = m.id
RETURNING *
)
INSERT INTO table (columnA, columnB, columnC, columnD)
SELECT columnA, columnB, columnC, columnD
FROM (VALUES ($value1, $value2, $value3, $value4, $value5),
($value6, $value7, $value8, $value9, $value10)
) c(columnA, columnB, columnC, columnD, id)
WHERE NOT EXISTS (SELECT 1 FROM updated_items ui WHERE ui.id = c.id::int);