总和多个列

时间:2016-04-05 03:32:56

标签: php mysql pdo

我的数据存储在我的MySQL(paid)中。我需要对列进行总结。

$sql= "SELECT SUM(furniture) FROM paid"; 
$stmt = $connect->prepare($sql);
$stmt->execute();
$furniture = (int) $stmt->fetchColumn();

$sql= "SELECT SUM(groceries) FROM paid"; 
$stmt = $connect->prepare($sql);
$stmt->execute();
$groceries = (int) $stmt->fetchColumn();

//so on....

数据库中有morthan 50列。我的问题是,有没有更短的方法来写这个,所以我可以获得每列的SUM并将其分配给变量?

3 个答案:

答案 0 :(得分:1)

尝试单一查询

$sql = "SELECT  SUM(`furniture`) AS sumFurniture, 
                SUM(`groceries`) AS sumGroceries ,
                ...
        FROM `paid` ";

结果可以通过

获得
$sth = $connect->prepare($sql);
$sth->execute();
$result = $sth->fetch();

$sumFurniture = $result['sumFurniture'];
$sumGroceries = $result['sumGroceries'];
....

答案 1 :(得分:0)

您可以将它们组合为单个SQL查询

SELECT SUM(furniture) AS furniture, SUM(groceries) AS groceries....... FROM paid 

答案 2 :(得分:-1)

如果您的r子句相同,您可以像这样组合查询:

where

从php,您可以获取它:使用数组索引" column_name1"," column_name2"