增加对帖子的回复总数


Increment total replies to a post

在我的数据库中,我有以下帖子结构:

post_id | reply_to | parent_id
   1         1           1
   2         1           1
   3         2           1
   4         3           1

因此,在这种情况下,post_id 1是主帖子,而post_id 2是对post_id的回复,post_id3是对post_i2的回复,并且post_id是对post_I3的回复。

我想做的是添加另一个列来跟踪帖子的回复总数。所以最后,表格会是这样的:

post_id | reply_to | parent_id | total_replies
   1         1           1            3
   2         1           1            2
   3         2           1            1
   4         3           1            0

如果我想更新回复总数,查询会是什么样子?

谢谢。:)

如果你只想对每个帖子进行简单的计算,你可以这样做:

UPDATE  posts 
        LEFT JOIN
        (
            SELECT post_id , (SELECT count(*) from posts p0 where p.post_id = p0.reply_to) as total_replies
            FROM posts p 
        ) p2 ON posts.post_id  = p2.post_id 
SET     posts.total_replies =p2.total_replies;

看到它在那里工作:http://sqlfiddle.com/#!2/868c6/1

现在,您想要的是执行递归读取,以计算回复,直到它到达顶部帖子。更糟糕的方法是在查询数据时计算它,所以当你保存一篇新文章时,你可以在PHP中这样做,或者在数据库中创建一个存储过程/函数,它将类似于:

$total_reply = 0;
function calculateTotalReply($postId)
{
    //Make the simple sum as I did above
   $total_reply = $sum;
    //Check if is the top post
    if(!$isTheTopPost)
    {
         calculateTotalReply($parentPost);
    }
}

所以,正如你所看到的,它会自称,直到达到最高职位,最终在$total_reply,你会得到你想要的金额。

类似于:

update posts p set total_replies = (select count(t.post_id) from 
posts t where t.reply_to = p.post_id)