2017-03-08 61 views
0

我有兩個表Table_ATable_B。我怎麼能寫一個條件SQL,做以下邏輯有條件刪除並插入postgres

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

回答

0

使用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 
     ); 

順便說一句:你應該有很好的理由(如想要激活觸發器)更喜歡刪除+插入到更新。

+0

是的。我試圖避免更新,因爲幾何複雜性 –