简体   繁体   English

有条件地删除并插入postgres

[英]Conditional delete and insert in postgres

I have two tables Table_A and Table_B . 我有两个表Table_ATable_B How can I write a conditional SQL that does the following logic 如何编写执行以下逻辑的条件SQL

If table A records match table B records on id
then
    delete records from table A and Insert records into Table B

How can I do this with SQL most likely using with 我该如何使用SQL最有可能with

delete from Table_A where Exists (select a.id from TABLE_A
join TABLE_B as b on a.id = b.id)

The Insert is: Insert into Table_A (id) select id from TABLE_B 插入为: Insert into Table_A (id) select id from TABLE_B

Use a CTE to catch the ids of the deleted records, and re-join these with the b records: 使用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
        );

BTW: you should have very good reasons (such as wanting to activate the triggers) to prefer delete+insert to a update. 顺便说一句:您应该有充分的理由 (例如想要激活触发器),希望删除+插入而不是更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM