简体   繁体   English

在while循环中总计mysql_num_rows

[英]Adding up total of mysql_num_rows in a while loop

For example I have a mysql_num_rows results of 4,8,15,16,23,42 in a query that is inside a while loop of another query. 例如,在另一个查询的while循环内的查询中,我的mysql_num_rows结果为4,8,15,16,23,42。 My question is how can I total all the results inside that while loop? 我的问题是我该如何在while循环中汇总所有结果? (Total of 133) Thanks. (共133个)谢谢。

EDIT: 编辑:

How about if I want to get the percentage per each result of mysql_num_rows inside my while loop? 如果我想在while循环中获取每个mysql_num_rows结果的百分比呢? Example: 4,8,15,16,23,42. 示例:4、8、15、16、23、42。 Total is 108. $sum = 108. Percentage of 4 = 4/$sum = 3.7%, 8 = 8/$sum = 7.4% and so on.. 总计为108。$ sum =108。百分比4 = 4 / $ sum = 3.7%,8 = 8 / $ sum = 7.4%,依此类推。

Try something like this: 尝试这样的事情:

$Sum = 0;
while ($SomeInvariant)
{
   mysql_query($SomeQuery);
   $Sum += mysql_num_rows();
}

echo 'The sum is: ' . $Sum;

However, this approach is not very efficient (what if $SomeInvariant is true for many iterations, and your app has even more concurrent users?). 但是,这种方法不是很有效(如果$SomeInvariant在许多迭代中都是正确的,并且您的应用程序有更多的并发用户,那该怎么办?)。 To account for this, I would recommend restructuring your approach so the addition is done in SQL. 为了解决这个问题,我建议重组您的方法,以便在SQL中完成添加。 This way, your query could look something like this: SELECT SUM(ColumnName) FROM ... . 这样,您的查询可能看起来像这样: SELECT SUM(ColumnName) FROM ...

UPDATE: Addressing follow-up question in the comments 更新:解决评论中的后续问题

If you don't already have the sum available from the query, then you'll have to loop over the dataset twice. 如果您还没有查询中可用的总和,那么您将不得不遍历数据集两次。 On the first pass, you'll calculate the sum. 在第一遍中,您将计算总和。 On the second pass, you'll calculate the ratio of each value to the sum. 在第二遍,您将计算每个值与总和的比率。

For example: 例如:

$Sum = 0;
$Rows = array();
while ($SomeInvariant)
{
   mysql_query($SomeQuery);
   $Value = mysql_num_rows();
   $Rows[] = $Value; // Push the value onto the row array
   $Sum += $Value;   // Add the value to the cumulative sum
}

echo 'The sum is: ' . $Sum;

foreach ($Rows as $Row)
{
    echo $Row . '/' . $Sum . ' = ' . number_format($Row / $Sum) . '%';
}

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

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