在while循环中总计mysql_num_rows [英] Adding up total of mysql_num_rows in a while loop

查看:70
本文介绍了在while循环中总计mysql_num_rows的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在另一个查询的while循环内的查询中,我的mysql_num_rows结果为4,8,15,16,23,42.我的问题是我该如何在while循环中汇总所有结果? (共133个)谢谢.

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. My question is how can I total all the results inside that while loop? (Total of 133) Thanks.

如果我想在while循环中获取每个mysql_num_rows结果的百分比呢?示例:4、8、15、16、23、42.总计为108.$ sum =108.百分比4 = 4/$ sum = 3.7%,8 = 8/$ sum = 7.4%,依此类推.

How about if I want to get the percentage per each result of mysql_num_rows inside my while loop? Example: 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..

推荐答案

尝试如下操作:

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

echo 'The sum is: ' . $Sum;

但是,这种方法效率不高(如果$SomeInvariant在许多迭代中都是正确的,并且您的应用程序有更多的并发用户,那该怎么办?).为了解决这个问题,我建议重组您的方法,以便在SQL中完成添加.这样,您的查询可能看起来像这样:SELECT SUM(ColumnName) FROM ....

However, this approach is not very efficient (what if $SomeInvariant is true for many iterations, and your app has even more concurrent users?). To account for this, I would recommend restructuring your approach so the addition is done in SQL. This way, your query could look something like this: 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.

例如:

$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) . '%';
}

这篇关于在while循环中总计mysql_num_rows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆