php-具有一个值和另一个值的记录之间的TIMEDIFF(),而不仅仅是一个值
作者:互联网
我有一张记录项目状态的表:
CREATE TABLE `project_states` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`state_id` INT(10) NULL DEFAULT NULL,
`project_id` INT(10) NULL DEFAULT NULL,
`created_at` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
一些假数据:
id | state_id | project_id | created_at
-----------------------------------------------------
1 | 2 | 8 | 2014-05-27 10:58:12
2 | 3 | 8 | 2014-05-27 11:10:34
3 | 8 | 8 | 2014-05-27 11:56:48
4 | 2 | 10 | 2014-05-27 11:08:34
5 | 4 | 10 | 2014-05-27 11:59:01
我试图得到两个状态(例如2和8)之间的时差,并且仅针对同时具有两个状态的项目;在这种情况下,仅适用于项目8(因为10没有状态8).
到目前为止,我已经设法选择了符合条件的项目(具有两个值,而不仅仅是一个值),但是此查询为每个匹配的项目返回结果的元组:
SELECT t.*
FROM (
SELECT ps.*
FROM project_states ps
WHERE ps.state_id IN (2,8)
) as t
JOIN project_states pro ON pro.project_id = t.project_id
WHERE pro.state_id = 8
正确返回:
id | state_id | project_id | created_at
-----------------------------------------------------
1 | 2 | 8 | 2014-05-27 10:58:12
3 | 8 | 8 | 2014-05-27 11:56:48
我非常确定它能正常工作,因为如果我将缺失的状态添加到另一个项目中,它将返回结果的新元组:
id | state_id | project_id | created_at
-----------------------------------------------------
1 | 2 | 8 | 2014-05-27 10:58:12
3 | 8 | 8 | 2014-05-27 11:56:48
4 | 2 | 10 | 2014-05-27 11:08:34
6 | 8 | 10 | 2014-05-27 12:03:08
但是如何计算时差?我正在使用PHP,我知道我可以通过project_id遍历结果,然后计算差异,但是我认为可能会有一个纯SQL解决方案,其产生的结果如下:
project_id | difference
------------------------
8 | 0000-00-00 01:02:00
10 | 0000-00-00 01:05:26
好吧,实际上,我的目标是计算项目在这两个选定状态之间的平均时差,因此所有记录都可以简化为一个平均值,但这可能是我稍后发现的一个问题.
解决方法:
如果只有两个状态,则可以使用简单的INNER JOIN.和TIMESTAMPDIFF()以分钟为单位进行计算,例如:
SELECT p.project_id,
TIMESTAMPDIFF(MINUTE,p.created_at,p1.created_at)
as state_minutes_diff
FROM project_states as p
JOIN project_states as p1
ON p.project_id=p1.project_id
AND p1.state_id=8
WHERE p.state_id=3
要获得所有项目的平均值:
SELECT AVG(TIMESTAMPDIFF(MINUTE,p.created_at,p1.created_at))
as AVG_state_minutes_diff
FROM project_states as p
JOIN project_states as p1
ON p.project_id=p1.project_id
AND p1.state_id=8
WHERE p.state_id=3
标签:date-math,sql,mysql,php 来源: https://codeday.me/bug/20191121/2053674.html