SQL组结果(按日期)

时间:2018-06-21 19:12:31

标签: php mysql sql ms-access

我无法按日期(特别是按天)对我获得的数据进行分组。

是否可以在sql内或使用pdo fetchall()做到​​这一点?

我知道如何在PHP中以“ lam式”方式执行此操作(遍历数据并对其进行处理,以获取所需的结构),但是是否有解决此问题的灵巧方法?

 $sql = "SELECT times.userid AS 'id', times.time AS 'time'
            FROM times
            WHERE ((times.userid) IN ($ids)) AND (times.time BETWEEN #$from# AND #$to#)
            ORDER BY times.time ASC;";

    $stmt = $db->prepare($sql); 
    $stmt->execute();

    $data = $stmt->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
    return $data;

使用上面的代码的结果是:

[815] => Array
        (
            [0] => 2018-01-01 05:00:00
            [1] => 2018-01-02 08:00:00
            [2] => 2018-01-03 03:00:00
            [3] => 2018-01-03 06:00:00
            [4] => 2018-01-04 03:00:00
            [5] => 2018-01-04 04:00:00
            [6] => 2018-01-05 01:00:00
            [7] => 2018-01-05 03:00:00
            [8] => 2018-01-08 04:00:00
            [9] => 2018-01-09 05:00:00
        )

我想要得到的结果是这样的:

[815] => Array
        (
            [2018-01-01] => Array
                            (
                                [0] => 2018-01-01 05:00:00
                            )
            [2018-01-02] => Array
                            (
                                [0] => 2018-01-02 08:00:00
                            )
            [2018-01-03] => Array
                            (
                                [0] => 2018-01-03 03:00:00
                                [0] => 2018-01-03 06:00:00
                            )
            [2018-01-04] => Array
                            (
                                [0] => 2018-01-04 03:00:00
                                [0] => 2018-01-04 04:00:00
                            )
            [2018-01-05 => Array
                            (
                                [0] => 2018-01-05 01:00:00
                                [0] => 2018-01-05 03:00:00
                            )
            [2018-01-08] => Array
                            (
                                [0] => 2018-01-08 04:00:00
                            )
            [2018-01-09] => Array
                            (
                                [0] => 2018-01-09 05:00:00
                            )
        )

0 个答案:

没有答案