从一个mysql查询返回两个SUM结果foreach循环

时间:2015-07-31 01:44:42

标签: php mysql foreach

我试图在一个查询中获取两个不同SUM的结果,因为我使用foreach来显示结果。实际上,第二个结果需要计算数据库中的记录数.PID = 3.我可以获得$ total SUM和$ conts为每个结果正确显示的唯一方法是使用ForEach循环,但我和#39;我不确定是否可以返回两个SUM结果,特别是因为第二个SUM / count" conts"有一个WHERE子句。

以下代码非常适合获取总数,但只要我添加:

SUM(points.PID WHERE points.PID = 3) AS conts

我没有结果。当然它应该是计数而不是SUM。这可能吗?我无法弄清楚这种方法。如果我需要对conts进行第二次查询,那么foreach如何知道将这些结果与循环中的正确记录相匹配?

$results = $dbh->prepare("select 
  wp_users.ID,
  wp_users.display_name,
  points.ID,
  points.PID,
 SUM(points.PID) AS total,
 SUM(points.PID WHERE points.PID = 3) AS conts
FROM points
LEFT JOIN wp_users ON points.ID=wp_users.ID
 GROUP BY points.ID ORDER BY total DESC
 LIMIT 5");
$results->execute();
$row = $results->fetchAll(PDO::FETCH_ASSOC);

//显示结果

foreach ($row as $all) {
echo "<td>$all7[total]</td>";
echo "<td>$all7[conts]</td>";

2 个答案:

答案 0 :(得分:0)

如果执行其中points.PID = 3作为子查询的总和(points.PID),您应该能够完成此任务。您的查询最终将是这样的:

SELECT  
  wp_users.ID,
  wp_users.display_name,
  points.ID,
  points.PID,
  SUM(points.PID) AS total,
  cnts.tot as conts
FROM points
  INNER JOIN (
    SELECT
      SUM(points.PID) as tot,
      ID
    FROM
      points
  ) cnts 
    ON cnts.ID = points.ID
  LEFT JOIN wp_users
    ON points.ID = wp_users.ID
GROUP BY points.ID 
ORDER BY total DESC
LIMIT 5

答案 1 :(得分:0)

您可以尝试SUM(IF(points.PID = 3, 1, 0)) AS conts