php MySQL查询两个日期时间,但如果在范围内完成,则包括来自外部范围的分钟

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (179)

我有一个gps php应用程序和一个包含路线旅行数据的数据库表:

START ROUTE(timeA)   END ROUTE(timeB)      DURATION   LENGHT (KM)
'2018-08-11 00:09:33', '2018-08-11 01:06:36', '57:3 ', '53.29'
'2018-08-11 01:17:06', '2018-08-11 01:25:58', '8:52 ', '7.11'
'2018-08-11 01:49:24', '2018-08-11 01:49:44', '20 ', '0.05'
'2018-08-11 02:05:49', '2018-08-11 02:25:39', '19:50 ', '15.30'
'2018-08-11 02:35:20', '2018-08-11 03:54:24', '1:19:4 ', '84.62'

.............

我需要计算日期间隔和小时间隔之间每天的总和。

我已经对此进行了查询:

$quu = ("SELECT SEC_TO_TIME(SUM(UNIX_TIMESTAMP(timeB) - UNIX_TIMESTAMP(timeA))) AS period, SUM(lenght) AS lenght FROM apm_travel_sheet WHERE timeA BETWEEN '$zistart' AND '$ziend' AND imei='$imei' ORDER BY timeA ASC");
$ress = mysql_query($quu) or die(mysql_error());
while($row = mysql_fetch_array($ress)) {
    $period = $row['period'];
    $lenght = round($row['lenght'], 2);

它运行良好,但如果路径在搜索间隔小时之前开始并以间隔结束,则查询不包括间隔的分钟。示例:我想为此时间间隔运行查询:start:2018-08-01 22:00 end:2018-08-02 06:00

如果在DB中我有一条路线从2018-08-01 21:46开始并在2018-08-02 22:40结束,结果它没有显示,因为start不在间隔中。我需要修改查询以显示40分钟,因为在选定的时间间隔内,我不知道...

谢谢你的帮助!

提问于
用户回答回答于
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,start_dt DATETIME
,end_dt DATETIME 
,distance_km DECIMAL(6,2)
);

INSERT INTO my_table VALUES
(1, '2018-08-11 00:09:33', '2018-08-11 01:06:36', 53.29),
(2, '2018-08-11 01:17:06', '2018-08-11 01:25:58',  7.11),
(3, '2018-08-11 01:49:24', '2018-08-11 01:49:44',  0.05),
(4, '2018-08-11 02:05:49', '2018-08-11 02:25:39', 15.30),
(5, '2018-08-11 02:35:20', '2018-08-11 03:54:24', 84.62),
(6, '2018-08-01 21:46:00', '2018-08-02 22:40:00', 50.05); 

SELECT * FROM my_table WHERE end_dt >= '2018-08-01 22:00' AND start_dt <= '2018-08-02 06:00';
+----+---------------------+---------------------+-------------+
| id | start_dt            | end_dt              | distance_km |
+----+---------------------+---------------------+-------------+
|  6 | 2018-08-01 21:46:00 | 2018-08-02 22:40:00 |       50.05 |
+----+---------------------+---------------------+-------------+

扫码关注云+社区

领取腾讯云代金券