我有一个页面,可以在数据库中动态查找注释和回复,并相应地生成代码。现在,我想计算每条评论的回复数量(下表中的comment_id
),如果它们超过3,则显示"There are XX replies"
,否则会显示所有回复。
回复表看起来像这样
+---------------------+----+---------+------------------+------------+
| 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
是父亲的回复(a.k.a.评论)
到目前为止,我所尝试的是:
$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
}
答案 0 :(得分:0)
您可以按查询分组查找回复计数。然后使用这些结果,您可以相应地显示文本。
SELECT comment_id, count(*) FROM replies GROUP BY comment_id
答案 1 :(得分:0)
您可以使用此查询:
选择回复,(从回复replies_inner中选择count(*),其中replies_inner.comment_id = replies.comment_id)作为回复中的reply_count
然后你可以循环访问php:
box-sizing: border-box
答案 2 :(得分:0)
所以我设法解决了这个问题,部分感谢@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'];
}