[英]Conditional delete and insert in postgres
我有两个表Table_A
和Table_B
。 如何编写执行以下逻辑的条件SQL
If table A records match table B records on id
then
delete records from table A and Insert records into Table B
我该如何使用SQL最有可能with
delete from Table_A where Exists (select a.id from TABLE_A
join TABLE_B as b on a.id = b.id)
插入为: Insert into Table_A (id) select id from TABLE_B
使用CTE捕获已删除记录的ID,然后将其与b记录重新连接:
WITH del AS (
DELETE FROM a
WHERE EXISTS ( SELECT *
FROM b
WHERE b.id = a.id
)
returning *
)
INSERT INTO a (id, x, y, z)
SELECT id, x, y, z
FROM b
WHERE EXISTS (
SELECT *
FROM del
WHERE del.id = b.id
);
顺便说一句:您应该有充分的理由 (例如想要激活触发器),希望删除+插入而不是更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.