2017-03-08 42 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

是的。我试图避免更新,因为几何复杂性 –