【问题标题】:Mysql - PHP - View Sum ColumnMysql - PHP - 查看总和列
【发布时间】:2015-08-05 05:46:17
【问题描述】:

如何查看列 (Collections) where (userid = $userid) 的总和?

示例:我需要查看用户 id = 2、Collections = 200 + 330 = 530 的结果,我需要查看此结果 (530)

我的桌子

------------------------------
| id | user_id | Collections |
------------------------------
| 1  |    2    |     200     |
------------------------------
| 2  |    2    |     330     |
------------------------------
| 3  |    7    |     120     |
------------------------------
| 4  |    8    |     760     |
------------------------------
| 5  |    9    |     200     |
------------------------------
| 6  |    9    |     100     |
------------------------------

我的代码

<?php

$user_id = get_current_user_id();

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$query = "SELECT SUM(Collections) FROM invoices where user_id = $user_id"; 

$result = mysql_query($query) or die(mysql_error());



// Print out result

?>
  • 我是 php & mysql 的初学者

【问题讨论】:

    标签: php mysql sql select mysqli


    【解决方案1】:

    你可以试试这个:

    SELECT SUM(i.Collections) AS totalCollection
    FROM invoices AS i
    WHERE i.user_id = '$user_id'
    GROUP BY i.user_id
    

    【讨论】:

    • @BakirOdeh 注意:- 在查询中使用GROUP BY,否则在删除where 子句时会遇到一些麻烦。
    【解决方案2】:

    试试这个

    SELECT SUM(Collections) AS totalvalue FROM invoices where user_id = '$user_id'
    

    打印结果totalvalue

    【讨论】:

      【解决方案3】:

      第一

      • 检查您的收集栏类型。是字符串/整数/日期吗?它应该是数字(Int、double、float)

      第二

      • 您的查询已经正确。但是列名你应该把它改成结果

      SELECT SUM(Collections) as result FROM invoices where user_id = $user_id
      

      然后检查您的功能,从连接中您使用的是 mysqli 但在您的查询中您使用的是 mysql 这个应该更改为相同的功能。


      解决方案

      <?php
      
      $user_id = get_current_user_id();
      
      $servername = "localhost";
      $username = "root";
      $password = "root";
      $dbname = "dbname";
      
      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);
      
      // Check connection
      if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
      } 
      
      $query = "SELECT SUM(Collections) FROM invoices where user_id = $user_id"; 
      
      $result = mysqli_query($link, $query) or die('query error');
      
      print_r($result);
      // Print out result
      
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-13
        • 1970-01-01
        相关资源
        最近更新 更多