【问题标题】:Retrieve number of replies to a comment检索评论的回复数
【发布时间】:2021-02-01 15:38:07
【问题描述】:

我有以下 PostgreSQL 表来存储不同帖子上的 cmets:

评论表:

commentID | parentID | postID | content | author | created

我现在想用一个查询来检索,给定一个 postID,该帖子的所有 cmets 以及每个评论的回复数。如果 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;

【问题讨论】:

    标签: sql postgresql count left-join lateral-join


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多