使用foreach语句回显MySQL行的SUM

时间:2017-05-21 11:33:35

标签: php mysql pdo sum

我有点担心如何做到这一点;我是所有这些PDO的新手,还没有完全习惯它。基本上,我有两个表,航班和用户。我想查找所有航班的名称,然后查看用户表,并将航班等于其中一个航班名称的“点”列汇总。这是我到目前为止所做的事情,我无法继续进步

select t.*
from t 
where t.rank >= (select min(t2.rank) from t t2 where t2.title_id = t.title_id and t2.Title_Pre_Status_Name = 'Annotate WO') and
      t.rank <= (select max(t2.rank) from t t2 where t2.title_id = t.title_id and t2.Title_Pre_Status_Name = 'New Work Order');

1 个答案:

答案 0 :(得分:4)

您需要在sql中获取sum字段。您可以为其添加别名以获得更好的清晰度。在fetchAll&amp;之后获得该值然后简单地将它放到$flightTotalPoints数组

$flightTotalPoints = [];
$qry = "SELECT flight, SUM(points) as total_sum  FROM users WHERE flight=:flightName ORDER by SUM(points) DESC";
$stmt = $_dbConn->prepare($qry); 
foreach ($flightRows as $flight) {
    $flightName = $flight["name"];
    $stmt->execute(["flightName" => $flightName]);
    $flightTotalPoints[$flightName] = $stmt->fetchAll()[0]['total_sum'];
}