【问题标题】:Sum of MYSQL QueryMYSQL 查询总和
【发布时间】:2018-12-29 14:41:59
【问题描述】:

我有一个 MySQL 数据库

我想在我的列中获取值的总和或总计,我需要回显它以在 Google Graphs 中使用

这是我当前的代码

 <?php 
        $query = "SELECT * from activation";

         $exec = mysqli_query($con,$query);
         while($row = mysqli_fetch_array($exec)){

         echo "['".$row['type']."',".$sum['type']."],"; 
         }
         ?> 

行类型是我想要得到的值,它们的值与 HIJACKING ACCIDENT 不同,等等值是恒定的。

我知道的 $sum 是错误的,但这是我需要回显行类型总数的地方

以下代码有效

 <?php 
            $query = "SELECT type, count(type) from activation group by type";

             $exec = mysqli_query($con,$query);
             while($row = mysqli_fetch_array($exec)){

             echo "['".$row['type']."',".$row['count(type)']."],";
             }
             ?> 

【问题讨论】:

  • 你为什么不SUM() in 查询呢?
  • ^^ this 或 $sum += $row['type'];(在此之前初始化 $sum=0)- 然后是 echo $sum
  • SELECT type, count(type) from activation group by type 怎么样?
  • 您的回声线看起来像是您尝试构建一个 json 字符串。不要那样做。构建一个数组,然后对其进行 json_encode。

标签: php mysql sum


【解决方案1】:

我想这是您应该使用的更精确的代码。我将您的count(type) 的别名用作act_type。希望这会有所帮助:)

<?php 
    $query = "SELECT type, count(type) as act_type from activation group by type";
    $exec = mysqli_query($con,$query);
    $expected = [];
    while($row = mysqli_fetch_array($exec)){
         $expected[$row['type']] = $row['act_type'];
         echo "['".$row['type']."',".$row['act_type']."],"; // you can use this line just for printing purpose
   }
   // use $expected array as you wish any where in your code, it contains your result as key=>value manner
?> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多