我想编写一个查询,如果我使用变量,它看起来像(伪代码)
records = SELECT * FROM table_1 WHERE id = x
numberOfRowsUpdated = UPDATE table_2 SET column_1 = y WHERE id = record1.id
INSERT INTO table2 (columns) (records.id, records.name, ...) where records exists and numberOfRowsUpdated == 0
目前,我有类似的东西,但语法似乎无效。有人能够提供有关在
WHERE
子句中包含更新声明的任何帮助吗?
WITH records AS (SELECT id, tx_id FROM table_1 WHERE id = NEW.id)
INSERT INTO table_2 (id,txn_id)
SELECT records.id, records.txn_id)
FROM records
WHERE EXISTS (SELECT 1 FROM records)
AND (UPDATE table_2 SET has_txn = true WHERE id in (records.id) = 0)
我让它以一种不稳定的方式工作,我想改进它,这样我就不会多次查询记录
WITH records AS (SELECT * FROM table_1 WHERE txn_id = NEW.id),
numberOfRowsUpdated AS (
UPDATE table_2 SET has_txn = true WHERE id in (SELECT id FROM
table_1 WHERE txn_id = NEW.id) RETURNING 1
)
INSERT INTO balance_activity_outbox (
id,
...
) SELECT (
records.id,
...
)
FROM records, numberOfRowsUpdated
WHERE EXISTS (SELECT 1 FROM records)
AND (select count(*) from numberOfRowsUpdated) = 0;
就像 Laurenz 已经怀疑的那样,看起来 UPSERT 可以做到:
INSERT INTO balance_activity_outbox (id, ...)
SELECT id, ...
FROM table_1
WHERE txn_id = NEW.id
ON CONFLICT (id) DO UPDATE
SET has_txn = true
WHERE has_txn IS NOT TRUE;
需要
balance_activity_outbox(id)
上的唯一约束/索引或主键。
我添加了最后一个
WHERE has_txn IS NOT TRUE
来取消空更新。仅当这种情况发生时才有用。参见: