我在Netezza中使用if not exists语句时遇到问题。我试图检查记录是否不存在然后插入其他更新记录。我在Netezza找不到更好的办法。这是我有的但不起作用:
IF NOT EXISTS(SELECT ID FROM OLD_TABLE WHERE ID NOT IN (SELECT ID FROM NEW TABLE ) )
INSERT INTO NEW_TABLE (NAME, LOCATION)
ELSE
UPDATE NEW_TABLE
SET NAME = X.NAME
FROM (SELECT NAME, LOCATION FROM OLD_TABLE)AS X
WHERE X.NAME = NEW_TABLE.NAME
答案 0 :(得分:4)
假设您提供了一个ID,并希望在new_table
中使用来自old_table
的值替换一行。我使用的是data-modifying CTE,需要Postgres 9.1或更高版本:
WITH input AS (SELECT 123 AS id)
, upd AS (
UPDATE new_table n
SET name = o.name
, location = o.location
FROM old_table o, input i
WHERE n.id = o.id
AND n.id = i.id
RETURNING id
)
INSERT INTO new_table (id, name, location)
SELECT o.id, o.name, o.location
FROM old_table o, input i
WHERE NOT EXISTS (SELECT 1 FROM upd)
AND o.id = i.id;
这是一个密切相关的答案,有更多解释:
Problems with a PostgreSQL upsert query
竞争条件很小。如果您计划在繁重的并发负载下使用此功能,请考虑此相关问题以及更多链接:
Upsert with a transaction
要整张整个表格:
WITH upd AS (
UPDATE new_table n
SET name = o.name
, location = o.location
FROM old_table o
WHERE n.id = o.id
RETURNING id
)
INSERT INTO new_table (id, name, location)
SELECT o.id, o.name, o.location
FROM old_table o
LEFT JOIN upd u USING (id)
WHERE u.id IS NULL;