简体   繁体   中英

Returning two SUM results in foreach loop from one mysql query

I am trying to get the results of two different SUMs in one query because I am using a foreach to display the results. Actually the second result needs to be a count of how many records in the database points.PID = 3. The only way I can get the $total SUM and $conts to display properly for each result is to use a ForEach loop, but I'm not sure it is possible to have two SUM results returned, especially since the second SUM/count "conts" has a WHERE clause.

The code below works great for getting total, but as soon as I add:

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

I get no results. Of course it should be count and not SUM anyway. Is this possible? I can't figure out the approach. If I need a second query for conts, how would the foreach know to match those results with the correct record in the loop?

$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);

//Display Results

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

If you perform the sum(points.PID) where points.PID = 3 as a subquery, you should be able to accomplish this. Your query would end up being something like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM