0
<?php
        include "connect.php";
        // Make a MySQL Connection
        $sql = "SELECT COUNT(*) AS comment FROM comment co INNER JOIN item i WHERE co.items= i.items GROUP BY i.items"; 
        $result = $mysqli->query($sql); 
        while ($row = $result->fetch_array(MYSQLI_ASSOC))
        {
        ?>
        No of Comments:&nbsp;<?php echo $row['comment'];?>
        <?php
        }
        ?>

它像这样回响:示例:

评论数:7 评论数:7

请帮忙!谢谢!

4

4 回答 4

4

那是因为你使用GROUP BY. 这意味着您可以获得i.items表中每个不同的计数。

您可以通过将该项目添加到查询结果中来检查(我更改WHEREON):

SELECT 
  i.items,
  COUNT(*) AS comment 
FROM 
  comment co 
  INNER JOIN item i ON co.items = i.items 
GROUP BY 
  i.items

解决方案是指定您想要的项目....

SELECT 
  i.items,
  COUNT(*) AS comment 
FROM 
  comment co 
  INNER JOIN item i ON co.items = i.items 
WHERE
  i.items = 'foo'
/* -- Grouping not needed anymore, since you only have 1 item (= 1 group)
GROUP BY 
  i.items*/ 

...或不分组,因此您可以获得所有项目的总数:

-- Will fetch the total number of comments (that are linked to an item)
SELECT 
  COUNT(*) AS comment 
FROM 
  comment co 
  INNER JOIN item i ON co.items = i.items 

... 或限制结果 此查询仅截断结果,仅返回其中一项的计数。该项目现在或多或少是随机选择的,尽管您可以添加 ORDER BY 来影响它。

SELECT 
  COUNT(*) AS comment 
FROM 
  comment co 
  INNER JOIN item i ON co.items = i.items 
GROUP BY 
  i.items
/* -- Optional order, if you need to influence which of the items is preffered.
ORDER BY 
  i.items*/
LIMIT 1

因此,从您的问题中,我只能说出问题所在,而不是哪种解决方案最适合您。但这里有几个选项可供选择。:)

于 2013-01-08T10:01:24.323 回答
0

你检查过co.items 和i.items 的不同值吗?由于您正在对项目进行分组,因此似乎有 2 个不同的值,因此每一行代表不同的项目值

试试这个来调试:

$sql = "SELECT COUNT(*) AS comment, i.items AS itemTest FROM comment co INNER JOIN item i WHERE co.items= i.items GROUP BY i.items"; 
    $result = $mysqli->query($sql); 
    while ($row = $result->fetch_array(MYSQLI_ASSOC))
    {
    ?>
    No of Comments:&nbsp;<?php echo $row['comment'];?> <?php echo $row['itemTest'];?> <br />
    <?php
    }
    ?>

你还需要加入和组吗?你打算它做什么?如果代码在特定项目的页面上,您应该能够做到

$sql = "SELECT COUNT(*) AS comment FROM comment co WHERE co.items= 'ITEM-IDENTIFIER-HERE' "; 
    $result = $mysqli->query($sql); 
    $row = $result->fetch_array(MYSQLI_ASSOC);
    ?>
    No of Comments:&nbsp;<?php echo $row['comment'];?>

尽管在查询、sql 注入和所有其他操作中使用项目标识符之前,自然会采取预防措施来清理项目标识符

于 2013-01-08T10:09:02.360 回答
0

尝试这个

<?php

include "connect.php";
        // Make a MySQL Connection
        $sql = "SELECT COUNT(*) AS comment FROM comment co INNER JOIN item i WHERE co.items= i.items GROUP BY i.items"; 
        $result = mysql_query($sql);

echo "No of Comments:&nbsp;". mysql_result($result, 0);

?>
于 2013-01-08T10:03:48.170 回答
0

你总是可以扔一个 LIMIT 1;在查询结束时,这可能不是构建语法的方式,但在不知道您的数据是什么的情况下,肯定有一种简单的方法可以获得您期望的结果:

替换
$sql = "SELECT COUNT(*) AS comment FROM comment co INNER JOIN item i WHERE co.items= i.items GROUP BY i.items";

with $sql = "SELECT COUNT(*) AS comment FROM comment co INNER JOIN item i WHERE co.items= i.items GROUP BY i.items LIMIT 1";

于 2013-01-08T10:05:46.377 回答