3个表的列中所有数字的总和?

时间:2016-05-22 21:06:40

标签: php sql

我正在尝试使用PHP和SQL来回显3个独立表中的列总和。我想知道如何简化它,因为它非常臃肿。

谢谢!

public function getTotalSum() {
    include("dbconnect.php");
    $query1 = "SELECT SUM(column1) AS 'count' FROM table1";
    $query2 = "SELECT SUM(column2) AS 'count' FROM table2";
    $query3 = "SELECT SUM(column3) AS 'count' FROM table3";
    $result1 = mysqli_query($sqlcon, $query1);
    $result2 = mysqli_query($sqlcon, $query2);
    $result3 = mysqli_query($sqlcon, $query3);

    if (mysqli_num_rows($result1) > 0 && mysqli_num_rows($result2) > 0 && mysqli_num_rows($result3) > 0) {
        while ($row = $result1->fetch_assoc() + $result2->fetch_assoc() + $result3->fetch_assoc()) {
            echo $row['count'];
        }
    }
}

1 个答案:

答案 0 :(得分:3)

使用一个sql查询而不是多个查询。
采用以下方法:

public function getTotalSum() {
    include("dbconnect.php");
    $query = "SELECT 
                (SELECT SUM(column1) AS 'count' FROM table1)
                + (SELECT SUM(column2) AS 'count' FROM table2)
                + (SELECT SUM(column3) AS 'count' FROM table3) AS count;    
    ";
    $result = mysqli_query($sqlcon, $query);

    if (mysqli_num_rows($result) > 0) {
        $row = $result->fetch_assoc();
        echo $row['count'];
    }
}