Using return value from DELETE for UPDATE in Postgres

前端 未结 1 529
萌比男神i
萌比男神i 2021-02-07 15:40

I need to update a table using a value deleted from another table. The situation is a comment vote scorekeeper similar to the one on SO. I\'m using python to work the postgres,

1条回答
  •  囚心锁ツ
    2021-02-07 16:06

    PostgreSQL doesn't allow mix UPDATE and DELETE statements as subquery.

    You can use a little bit different strategy - updateable CTE

    postgres=# WITH t1 AS (DELETE FROM foo RETURNING *), 
                    t2 AS (INSERT INTO deleted 
                              SELECT * FROM t1 RETURNING *) 
                 SELECT max(a) FROM t2;
    

    so

    postgres=# CREATE TABLE comment(id int, score int);
    CREATE TABLE
    postgres=# CREATE TABLE history(id int, comment_id int, vote int);
    CREATE TABLE
    postgres=# INSERT INTO comment values(1,10);
    INSERT 0 1
    postgres=# INSERT INTO comment values(2,20);
    INSERT 0 1
    postgres=# INSERT INTO history values(1,1,5);
    INSERT 0 1
    postgres=# WITH t1 AS (DELETE FROM history 
                           WHERE id=1 
                           RETURNING comment_id, vote) 
               UPDATE comment SET score=score-t1.vote 
               FROM t1 
               WHERE t1.comment_id=comment.id;
    UPDATE 1
    postgres=# select * from comment;
     id | score 
    ----+-------
      2 |    20
      1 |     5
    (2 rows)
    

    Attention: It require 9.1 or newer

    0 讨论(0)
提交回复
热议问题