简体   繁体   English

MySQL在while循环中显示1个结果…但是实际上它们有2个结果?

[英]MySQL displaying 1 result within while loop…however theirs actually 2 results?

I recently combined 2 queries into 1 (to optimize performance)...1 query for checking the count, and the other for the results, the count is to ensure their is actual results their before proceeding with the loop. 我最近将2个查询合并为1个(以优化性能)... 1个查询以检查计数,另一个查询结果,计数是为了确保它们是实际结果,然后再进行循环。

Heres the PHP code: 这是PHP代码:

<?php

    $query = 'SELECT id, title, COUNT(id) FROM submissions ORDER BY sub_time DESC LIMIT 50';

    $result = mysql_query($query);

    $count = mysql_result($result, 0, 2);

    mysql_data_seek($result, 0); //mysql_result resets the internal pointer...

    if ($count > 0) {
        $i = 0;
        while ($output = mysql_fetch_assoc($result)) {
            ++$i;

            //etc..

        }
    }


?>

The problem is it now returns 1 result? 问题在于它现在返回1个结果? - when theirs actually 2 results inside (as I've checked via PHPMyAdmin aswell as running the following code - see below), I've narrowed down the problem, its because the COUNT(id) has been combined with the intial results query; -当他们的结果实际上是2个(当我通过PHPMyAdmin检查并运行以下代码-参见下文)时,我已经缩小了问题的范围,因为COUNT(id)已与初始结果查询结合在一起; that its behaving like this. 它的行为是这样的。

Because if I do the following: 因为如果执行以下操作:

<?php

    $query = 'SELECT id, title FROM submissions ORDER BY sub_time DESC LIMIT 50';

    $result = mysql_query($query);

        $i = 0;
        while ($output = mysql_fetch_assoc($result)) {
            ++$i;

            //etc..

        }

?>

It returns 2 results... 它返回2个结果...

So my question is how do i resolve this but achieve what I'm after? 所以我的问题是我该如何解决这个问题,但要实现我的追求?

I would recommend that you remove the COUNT(id) and use the mysql_num_rows() function to check how many rows were returned before trying to loop through them. 我建议您删除COUNT(id)并使用mysql_num_rows()函数在尝试遍历它们之前检查返回的行数。

Your code could then look like this: 您的代码如下所示:

<?php

$query = 'SELECT id, title FROM submissions ORDER BY sub_time DESC LIMIT 50';

$result = mysql_query($query);

$count = mysql_num_rows($result);

if ($count > 0) {
    $i = 0;
    while ($output = mysql_fetch_assoc($result)) {
        ++$i;

        //etc..

    }
}

COUNT is an aggregate function that typically is used with the GROUP BY clause. COUNT是通常与GROUP BY子句一起使用的聚合函数 I don't believe it is meaningful in the query as you used it. 我认为您使用它在查询中没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM