检索评论的回复数

问题描述

我有以下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;

解决方法

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

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;而且,不需要条件计数。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...