Postgres在事务中合并两个写查询

时间:2019-06-02 22:11:26

标签: sql postgresql

我正在尝试编写一个事务来更新两个不同表上的两行

BEGIN;

UPDATE comments SET upvoted = upvoted + 1 
WHERE comment_id = $1 AND posted_by = $2;

INSERT INTO commentsvoted(id, user_id, votes, thread_id) 
VALUES($1, $2, true, $3);

COMMIT;

此查询在pgadmin中有效,但在lambda中不起作用,并返回错误

cannot insert multiple commands into a prepared statement

我如何将这两个写入合并为一个语句?为何它在pgadmin之外不起作用?

1 个答案:

答案 0 :(得分:4)

在Postgres中,您可以将其编写为单个语句:

WITH u as (
      UPDATE comments
          SET upvoted = upvoted + 1 
          WHERE comment_id = $1 AND posted_by = $2
     )
INSERT INTO commentsvoted (id, user_id, votes, thread_id) 
    VALUES($1, $2, true, $3);