Php 如果一个表中有多个事件,如何计数和生成代码

Php 如果一个表中有多个事件,如何计数和生成代码,php,mysql,Php,Mysql,我有一个页面,动态地在数据库中查找注释和回复,并相应地生成代码。现在,我想计算下表中每个评论id的回复数,如果超过3条,则显示有XX条回复,否则显示所有回复 回复表如下所示 +---------------------+----+---------+------------------+------------+ | date | id | user_id | reply | comment_id | +--------------------

我有一个页面,动态地在数据库中查找注释和回复,并相应地生成代码。现在,我想计算下表中每个评论id的回复数,如果超过3条,则显示有XX条回复,否则显示所有回复

回复表如下所示

+---------------------+----+---------+------------------+------------+
| date                | id | user_id | reply            | comment_id |
+---------------------+----+---------+------------------+------------+
| xxxx-xx-xx xx:xx:xx |  1 |      01 | adasdasdasdasdas |          8 |
| xxxx-xx-xx xx:xx:xx |  2 |      02 | test             |          8 |
| xxxx-xx-xx xx:xx:xx |  3 |      03 | m  no            |          8 |
| xxxx-xx-xx xx:xx:xx |  4 |      03 | mno              |          8 |
| xxxx-xx-xx xx:xx:xx |  5 |      05 | hehe             |         10 |
+---------------------+----+---------+------------------+------------+
id是回复的id

user_id是编写注释的用户

comment_id是父亲回复的id,也称为comment

到目前为止,我尝试的是:

$querys = "SELECT * FROM replies 
            WHERE comment_id = {$writeComment['comment_id']} 
            ORDER BY date DESC;";

$findReplies = mysqli_query($_SESSION['connection'], $querys);

while ($reply = mysqli_fetch_assoc($findReplies)) {
    $countReplies = "SELECT * FROM replies
                    GROUP BY comment_id
                    HAVING COUNT( DISTINCT comment_id ) > 3;";

$moreThanThree = mysqli_query($_SESSION['connection'], $countReplies);

if(!$moreThanThree){
    // code for lass than 3 replies
} else {
    // there are xx replies
    // show  all replies
}

您可以使用group by查询来查找回复的数量。然后使用这些结果可以相应地显示文本

SELECT comment_id, count(*) FROM replies GROUP BY comment_id

您可以使用以下查询:

选择reply,选择count*from replets replets\u inner,其中replets\u inner.comment\u id=replets.comment\u id作为reply\u count from replets

然后,您可以循环使用php:

$previuos_comment=$rows[0]['comment_id'];
foreach($rows as $row) {
$reply_count =$row['reply_count '];
if($reply_count>3) {
echo 'xxxxxx';
} else {
if($previuos_comment==$row['comment_id']) {
echo $row['reply'];
}
$previuos_comment=$row['comment_id'];
}

}

所以我设法解决了这个问题,部分原因是@Gouda Elalfy:

while ($reply = mysqli_fetch_assoc($findReplies)) {

    $querya = "SELECT comment_id, (SELECT COUNT(*) FROM replies 
           WHERE comment_id = {$writeComment['comment_id']}) 
           AS reply_count FROM replies";


    $findHowMany = mysqli_query($_SESSION['connection'], $querya);
    $moreThanThree = mysqli_fetch_assoc($findHowMany);


        if($moreThanThree['reply_count'] < 3){
            //print comment
        } elseif (isset($prevId)){
           if(prevID != $reply['id']){
           // print "there are xx comments"
           break;
           }
        }

    $prevId = $reply['id'];
}

到目前为止你尝试了什么?