簡體   English   中英

有條件地刪除並插入postgres

[英]Conditional delete and insert in postgres

我有兩個表Table_ATable_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM