你如何循环并显示GROUP BY日期的MYSQL查询结果?

时间:2017-12-03 04:54:26

标签: php mysql

我有一个名为pools的表,每个条目都有poolidcreateddate。我为自己制作了一种仪表板,我希望看到过去一周每天创建的池数列表(包括"今天到目前为止#34;)。

我已经走到这一步了,但这简单地回吐了#34; 8",这实际上是今天到目前为止创建的池数,但是如何检索昨天,2天前的池数, 3天前等?

    $today= date('Y-m-d');
    $weekago=date('Y-m-d', strtotime('-1 week'));

        $stmt = $pdo->prepare("SELECT COUNT(*), poolid FROM pools WHERE `createddate` BETWEEN :weekago AND :today GROUP BY createddate ORDER BY createddate DESC");  
        $stmt->execute([':weekago' => $weekago, ':today' => $today]);
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $numpoolssofartoday= $stmt->rowCount();
        }

echo $numpoolssofartoday;

调整并获得以下内容以执行我想要的操作:

$stmt = $pdo->prepare("SELECT COUNT(*) as numpools, createddate FROM pools WHERE `createddate` BETWEEN :weekago AND :today GROUP BY createddate ORDER BY createddate DESC");  
$stmt->execute([':weekago' => $weekago, ':today' => $today]);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $numpoolspastweek .= date('m-d',strtotime($row['createddate'])) . " " . $row['numpools']. "<br>";
}

输出:

12-02 11
12-01 24
11-30 16
11-29 17
11-28 22
11-27 22
11-26 16
11-25 17

1 个答案:

答案 0 :(得分:1)

你的问题是你在编写输出:

result
你现在看到了吗? foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { $numpoolssofartoday= $stmt->rowCount(); } echo $numpoolssofartoday; 应该是一系列计数。或者至少你应该根据你想要做的事情在循环内输出。 (例如测试)。

此外,您使用$numpoolssofartoday计算查询的所有返回行。而不是使用查询返回的计数。

所以我会更改你的SQL以便更容易获得总数,并添加日期,poolid是无关紧要的,因为它是不正确的,因为你将多行与rowCount子句组合在一起/ p>

GROUP BY

此外,我会使用$sql = 'SELECT createddate, COUNT(poolid) AS total FROM ...'; // I'm to lazy for that looping, and been coding to much so I like to type as little as possible. $stmt->fetchAll(PDO::FETCH_GROUP); ,第一列是您分组的数据,因此您可以获得这样的数组,并且可以跳过循环。

Fetch Group