检索评论的回复数

Retrieve number of replies to a comment

我有以下 PostgreSQL table 来存储不同 post 的评论:

评论table:

commentID | parentID | postID | content | author | created

我现在想通过单个查询检索,给定一个 postID,对 post 的所有评论以及每个评论的回复数量。如果 parentID 不为 null 且等于其父项的 commentID,则评论是回复。

我尝试了类似下面的方法,我自己加入 table 并寻找 parentID = commentID 的匹配项,但我无法让它工作,希望得到一些帮助:)

SELECT comments.commentID as commentID, comments.parentID as parentID, comments.postID as postID,
comments.content as content, comments.author as author, comments.created as created,
COALESCE(c1.numReplies, 0) as numReplies
FROM comments c0
LEFT JOIN (
    SELECT parentID, COUNT(*) FILTER (WHERE postID = :givenPostID) as numReplies as numReplies
    FROM comments
) c1 on c0.commentID = c1.parentID
WHERE c0.postID = :givenPostID;

这看起来是子查询或横向连接的好地方:

select c.*, c1.no_replies
from comments c
cross join lateral (
    select count(*) no_replies
    from comments c1
    where c1.parentid = c.commentid
) c1 
where c.postid = :givenpostid

旁注 - 您想要编写的查询可能是:

SELECT c0.*, COALESCE(c1.numReplies, 0) as numReplies
FROM comments c0
LEFT JOIN (
    SELECT parentID, COUNT(*) as numReplies
    FROM comments
    GROUP BY parentID
) c1 on c0.commentID = c1.parentID
WHERE c0.postID = :givenPostID

子查询略有不同:首先,它需要一个 GROUP BY 子句才能有效 SQL;而且,不需要条件计数。