Postgres CTE 插入并获取计数

Postgres CTE Insert and get count

这是一个 CTE 查询。插入后,我想获得更新的计数。插入发生得很好,但计数 returns 是插入之前的计数,不包括新行。如果我在这里做错了什么,你能告诉我吗?

WITH reply_data(id, threadid, commentid, userid, description, created, updated) AS (
    VALUES ('27c12e17-b105-48fd-897b-82e5965ab15a'::uuid,
            'bbe04e77-0e53-4716-b001-81e7dbf40d70'::uuid,
            'fd2513fb-5e92-4a40-a295-6c122c325166'::uuid,
            '5b3a6120-233e-4b77-9160-c08c484db31b'::uuid,
            'Manual Reply to comment from SQL',
            now(),
            now())
),
     reply_insert AS (
         INSERT INTO replies (id, threadid, commentid, userid, description, created, updated)
             SELECT rd.id, rd.threadid, rd.commentid, rd.userid, rd.description, rd.created, rd.updated
             FROM reply_data rd
             RETURNING id, commentid
     ),
     user_reply_insert as (
         INSERT INTO user_replies (userid, replyid)
             SELECT rd.userid, rd.id FROM reply_data rd
             RETURNING userid
     ),
     replyCount as (
         select count(*) as repliescount
         from replies r,
              reply_data rd
         where r.commentid = rd.commentid
     )

SELECT repliescount FROM replyCount;

根据 Postgres document,具有 CTE 的查询的所有子语句几乎同时发生。也就是说,它们基于相同的数据库快照。

当插入 CTE 时,您将需要两个语句(在单个事务中)来说明您尝试执行的操作或使用总数据进行计算:

WITH reply_data(id, threadid, commentid, userid, description, created, updated) AS (
    VALUES ('27c12e17-b105-48fd-897b-82e5965ab15a'::uuid,
            'bbe04e77-0e53-4716-b001-81e7dbf40d70'::uuid,
            'fd2513fb-5e92-4a40-a295-6c122c325166'::uuid,
            '5b3a6120-233e-4b77-9160-c08c484db31b'::uuid,
            'Manual Reply to comment from SQL',
            now(),
            now())
),
     reply_insert AS (
         INSERT INTO replies (id, threadid, commentid, userid, description, created, updated)
             SELECT rd.id, rd.threadid, rd.commentid, rd.userid, rd.description, rd.created, rd.updated
             FROM reply_data rd
             RETURNING id, commentid
     ),
     user_reply_insert as (
         INSERT INTO user_replies (userid, replyid)
             SELECT rd.userid, rd.id FROM reply_data rd
             RETURNING userid
     ),
     replyCount as (
         select count(*) + (select count(*) from reply_insert) as repliescount
         from replies r,
              reply_data rd
         where r.commentid = rd.commentid
     )

SELECT repliescount FROM replyCount;