![](/img/trans.png)
[英]php function not returning all results from a MySQL query in a foreach
[英]Returning two SUM results in foreach loop from one mysql query
我试图在一个查询中获得两个不同的SUM的结果,因为我使用的是foreach来显示结果。 实际上,第二个结果需要计算数据库点中的记录数量。PID=3。我可以使$ total SUM和$ conts正确显示的唯一方法是使用ForEach循环,但是我我不确定是否有可能返回两个SUM结果,尤其是因为第二个SUM / count“ conts”具有WHERE子句。
下面的代码非常适合总计,但是一旦添加,就可以:
SUM(points.PID WHERE points.PID = 3) AS conts
我没有结果。 当然,它应该是计数而不是总和。 这可能吗? 我不知道这种方法。 如果我需要第二次查询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>";
如果执行sum(points.PID)(其中points.PID = 3)作为子查询,则应该能够完成此操作。 您的查询最终将是这样的:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.