计算MySQL中的时差但考虑事件

时间:2015-06-14 22:45:58

标签: mysql time

我有一个像这样的结构表

function getcookie (cookiename) {
    var cookie = "",
        cookies = document.cookie.split(";");
    cookies.forEach(function (item) {
        var keyvalue = item.split("="),
            key = keyvalue[0].trim(),
            val = keyvalue[1].trim();
        if (key === cookiename) {
            cookie = val;
            return false; //exit from iteration
        }
    });
    return cookie;
}

我想做的是计算开始和结束之间的时间(即索引1-4是30分钟,6-8是20分钟),但只考虑第一个开始和第一个结束,以便查询没有选择索引1-8的时差。哪个查询用于计算两个雕像之间的时差(起始端),并显示多个起始实例的结果,而不将它们分配到一个事件中?

2 个答案:

答案 0 :(得分:2)

考虑以下内容......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id  INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,dt DATETIME NOT NULL
,status VARCHAR(12) NOT NULL
);

INSERT INTO my_table VALUES
(1       ,'2015-01-01 13:00:00' ,  'start'),
(2       ,'2015-01-01 13:10:00' ,  'continue'),
(3       ,'2015-01-01 13:20:00' ,  'continue'),
(4       ,'2015-01-01 13:30:00' ,  'end'),
(5       ,'2015-01-01 13:30:00' ,  'ready'),
(6       ,'2015-01-01 13:40:00' ,  'start'),
(7       ,'2015-01-01 13:50:00' ,  'continue'),
(8       ,'2015-01-01 15:00:00' ,  'end');

SELECT x.*
     , TIMEDIFF(MIN(y.dt),x.dt)diff 
  FROM my_table x 
  JOIN my_table y 
    ON y.dt >= x.dt 
 WHERE x.status = 'start' 
   AND y.status = 'end' 
 GROUP 
    BY x.id;
+----+---------------------+--------+----------+
| id | dt                  | status | diff     |
+----+---------------------+--------+----------+
|  1 | 2015-01-01 13:00:00 | start  | 00:30:00 |
|  6 | 2015-01-01 13:40:00 | start  | 01:20:00 |
+----+---------------------+--------+----------+

答案 1 :(得分:1)

对于每次开始,使用查询来获取下一个结束时间。然后,只计算差异。逻辑是这样的:

select t.*, timestampdiff(second, dt, next_dt)
from (select t.*, addtime(t.date, t.time) as dt,
             (select addtime(t2.date, t2.time)
              from table t2
              where addtime(t2.date, t2.time) > addtime(t.date, t.time) and
                    status = 'end'
              order by addtime(t2.date, t2.time) desc
              limit 1
             ) as next_dt
      from table t
      where status = 'start'
     ) t

这假定您使用正确的数据库类型(datetime)存储日期和时间列。如果您将它们存储为其他内容,则必须不必要地将逻辑复杂化以将其转换为内部格式。