【问题标题】:Get total from amounts in rows MySQL PHP从行中的金额获取总额 MySQL PHP
【发布时间】:2011-10-17 21:55:59
【问题描述】:

我正在为我的游戏开发彩票系统,但我对总底池大小有疑问

当前进度:http://playsilab.com/lottery

无论如何,我正在做的是让用户在游戏中购买一张票,这将算作底池的 +5 货币。

这就是桌子的样子

基本上我需要它来计算所有那些 5000000 并输出 1 个数字 或者我的其他想法,获取人数和 *5 任何一个都会很棒:)

基本上8个人有5000000,应该打印出40000000(40M)

我的尝试:

$pot = mysql_query("SELECT name, SUM(pot), COUNT(name) FROM contestants");
$details = mysql_fetch_array($pot);
$totalpot = $details['SUM($details['pot']'];

【问题讨论】:

    标签: mysql count sum


    【解决方案1】:

    这一行是错误的:

    $totalpot = $details['SUM($details['pot']'];
    

    问题似乎是以下几种情况的结合:

    • 带引号的字符串中的非转义引号
    • 您的美元参考没有被评估,因为它在单引号内
    • 缺少括号
    • 只是通常不正确

    为您的列提供别名,以便在您的源代码中更容易地引用它们:

    SELECT SUM(pot) AS sum_pot, COUNT(name) AS count_name FROM contestants
    

    那么你可以写:

    $totalpot = $details['sum_pot'];
    

    您的代码还有许多其他问题,例如:

    • 在尝试访问结果之前,您没有检查查询是否失败。
    • 从单行返回name 和在同一结果集中返回聚合值(如SUM)几乎没有意义。在 MySQL 中这是合法的,但在许多其他数据库中,这将被视为错误而被拒绝。

    【讨论】:

      【解决方案2】:

      我的解决方案:

      list($totalpot) = @mysql_fetch_row(mysql_query("SELECT SUM(pot) FROM contestants WHERE pot=5000000"));
      list($count) = @mysql_fetch_row(mysql_query("SELECT COUNT(*) FROM contestants WHERE pot=5000000"));
      

      或者如果您想按底池金额计算总和

      $query = mysql_query("SELECT pot, SUM(pot) as sum_pot, COUNT(*) as count_pot FROM contestants GROUP BY pot");
      while($row = @mysql_fetch_assoc($query)) {
          // $row['pot'] is 50000
          // $row['sum_pot'] is 40M
          // $row['count_pot'] is 8
      }
      

      【讨论】:

        猜你喜欢
        • 2020-03-13
        • 1970-01-01
        • 2015-11-24
        • 2011-11-15
        • 2016-12-28
        • 2017-07-18
        • 1970-01-01
        • 1970-01-01
        • 2016-03-26
        相关资源
        最近更新 更多