gpt4 book ai didi

PHP mySQL 行之间的时间

转载 作者:行者123 更新时间:2023-11-29 03:25:02 24 4
gpt4 key购买 nike

你好,我被困在这个问题上了。希望能够从 mySQL 数据库中提取 2 个开始/停止行之间的时间。我的 table 看起来像这样

fillercdown_ndx |  time                 | B3_4_5
1 | 2016-06-16 14:59:45 | 0
2 | 2016-06-16 15:03:11 | 1

基本上当它记录为 0 时机器停止,当记录为 1 时机器重新启动。我需要能够计算机器在特定时间(例如上午 8 点至下午 5 点)之间停机的时间。打算使用 PHP 在用户输入时间时显示它,但不知道 SQL 命令。

有人知道找到这个的最佳方法吗?

创建表

CREATE TABLE `fillercdown` (
`fillercdown_ndx` int(11) NOT NULL AUTO_INCREMENT,
`time` datetime DEFAULT NULL,
`B3_4_5` int(11) DEFAULT NULL,
PRIMARY KEY (`fillercdown_ndx`),
KEY `fillercdowntimendx` (`time`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1

更新:

将有数百个这样的“开始”和“停止”条目。我的最终目标是在 php 中为用户提供一个小表格,要求他们提供一个时间范围,例如上午 8 点到下午 5 点,然后能够计算机器“停止”的所有时间(即 B3_4_5 为 0 时) ).我似乎无法找出正确的 SQL 调用来获取每个 0 和 1 之间的时间差并将它们在设定的时间范围内加在一起

最佳答案

这就是我目前用来做的事情,听起来就像你正在尝试做的那样。我正在使用 PDO,但如果您需要使用它,这可以很容易地适应 mysqli。这取决于按时间交替关闭/打开值。如果出于某种原因有任何连续的关闭或打开行,预期结果将变得不明确。

// First select everything in the requested range ordered by time.
$sql = "SELECT `time`, B3_4_5 FROM your_table WHERE `time` BETWEEN ? AND ? ORDER BY `time`";
$stmt = $pdo->prepare($sql);
$stmt->execute([$query_start, $query_end]);

// Initialize two DateTime objects (start and end) used to calculate the total time.
$total_start = new DateTime('00:00');
$total_end = clone $total_start;

$off = null;
while ($row = $stmt->fetchObject()) {
if ($row->B3_4_5) {
$on = new DateTime($row->time);
// increment total end time with difference between current off/on times
if ($off) {
$total_end->add($on->diff($off));
}
} else {
$off = new DateTime($row->time);
}
}

// total downtime is difference between start and end DateTimes
$total_downtime = $total_start->diff($total_end);

$total_downtime 是一个 DateInterval 对象。您可以使用其 format 返回一条消息方法:

echo $total_downtime->format('Total downtime: %h hours, %i minutes, %s seconds.');

关于PHP mySQL 行之间的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37870352/

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