Postgres-简化查询

时间:2019-06-04 18:21:18

标签: sql postgresql

我有一个返回true,false或null的查询

SELECT * FROM commentsvoted WHERE id = $1 AND user_id = $2;

接收到值后,我要根据返回的值执行另一个查询。

是真的:

UPDATE commentsvoted SET votes = NULL WHERE id = $1 AND user_id = $2;
UPDATE comments SET upvoted = upvoted - 1 
WHERE comment_id = $1 AND posted_by = $2;

如果为假:

UPDATE commentsvoted SET votes = true WHERE id = $1 AND user_id = $2;
UPDATE comments SET downvoted = downvoted - 1, upvoted = upvoted + 1 
WHERE comment_id = $1 AND posted_by = $2;

如果为空:

UPDATE commentsvoted SET votes = true WHERE id = $1 AND user_id = $2;
UPDATE comments SET upvoted = upvoted + 1 
WHERE comment_id = $1 AND posted_by = $2;

如何在一个查询中做到这一点?

1 个答案:

答案 0 :(得分:0)

在Postgres中,您可以在CTE(公用表表达式)中进行更新:

with t as (
      SELECT * FROM commentsvoted WHERE id = $1 AND user_id = $2
     ),
     cv as (
      UPDATE commentsvoted
          SET votes = (CASE WHEN t.value THEN NULL ELSE true END)
          FROM t
          WHERE id = $1 AND user_id = $2
     )
  UPDATE comments
      SET upvoted = (CASE WHEN t.value THEN upvoted - 1
                          WHEN t.value IS NULL THEN upvoted + 1
                          ELSE upvoted 
                     END),
          downvoted = (CASE WHEN NOT t.value THEN downvoted - 1
                            ELSE downvoted 
                       END)

      FROM t
      WHERE comment_id = $1 AND posted_by = $2;