我有以下 PostgreSQL 表来存储不同帖子的评论:
评论表:
commentID | parentID | postID | content | author | created
我现在想用一个查询来检索,给定一个 postID,对帖子的所有评论以及每个评论的回复数。如果 parentID 不为 null 并且等于其父项的 commentID,则评论是回复。
我尝试了类似以下的方法,我自己加入表格并查找匹配项,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;