gpt4 book ai didi

php - 有序 SQL 时间戳提取

转载 作者:行者123 更新时间:2023-11-29 06:31:15 30 4
gpt4 key购买 nike

首先,我试过搜索这个主题但一无所获(似乎找不到合适的关键词),所以如果这是重复的,请告知。

我一直在尝试从我的数据库中获取一些 time_stamp 并将它们按时间间隔排序。例如,我运行一个查询,如

"SELECT `time_stamp` FROM registo albufeira ".$nome."` WHERE `cota` > '".$piInfo['cota max']."'" 

并使用 php 代码来安排它的间隔。

例如,如果我有对应于以下日期的时间戳:

2014-12-30 23:51:00
2014-12-30 23:52:00
2014-12-30 23:53:00
2014-12-30 23:54:00
2014-12-31 01:35:00
2014-12-31 01:36:00
2014-12-31 01:37:00

我会得到一个间隔数组,例如:

[0] => Array
[0] => 2014-12-30 23:51:00
[1] => 2014-12-30 23:54:00
[1] => Array
[0] => 2014-12-31 01:35:00
[1] => 2014-12-31 01:37:00

我已经设法让 php 代码获得想要的结果,但我觉得这可以使用单个 SQL 查询来实现。谁能指出我正确的方向?

最佳答案

试试这个:

SELECT DATE(time_stamp) AS `day`, MIN(time_stamp) AS first, MAX(time_stamp) AS last
FROM `registo albufeira` # fix the table name
WHERE `cota` > '...' # put your condition here
GROUP BY DATE(time_stamp)

它会产生类似这样的东西:

+------------+---------------------+---------------------+
| day | first | last |
+------------+---------------------+---------------------+
| 2014-12-30 | 2014-12-30 23:51:00 | 2014-12-30 23:54:00 |
| 2014-12-31 | 2014-12-31 01:35:00 | 2014-12-31 01:37:00 |
+------------+---------------------+---------------------+

然后您可以通过 PHP 代码将其存储为所需的格式。

$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = array($row['first'], $row['last']);
}

上面的代码将生成您在问题中转储的数据结构,但我强烈建议您使用字符串键('day'、'first'、'last',无论您想要什么)而不是数字键:

$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[$row['day']] = $row;
}

添加一个 print_r($data); 并检查差异。

更新:

如果间隔的长度不是一天而是 300 秒,则将 DATE(time_stamp) 替换为 UNIX_TIMESTAMP(time_stamp) DIV 300

关于php - 有序 SQL 时间戳提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27797639/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com