我在MySQL中有一个表格,格式为:(时间=插入时间戳)
id | tid | uid | time
31 | 1 | 14 | 2011-05-19 05:42:37 //start timestamp)
41 | 1 | 14 | 2011-05-19 07:18:42 //stop timestamp)
45 | 1 | 14 | 2011-05-19 07:18:49 //start timestamp)
46 | 1 | 14 | 2011-05-19 07:28:42 //stop timestamp)
我需要的是制作一个像这样添加时差的选择
(41 - 31) + (46 - 45)
(我正在使用id而不是实际的time
值来更好地理解我需要做什么)
类似于SELECT (something that does this) AS TotalTimeSpent WHERE tid = '1'
答案 0 :(得分:2)
如果你坚持使用这个表格布局(我真的希望你改变主意,这真的很可怕),你可以用存储过程中的游标来做。
伪代码将是这样的:
CREATE PROCEDURE gettotaltime()
BEGIN
DECLARE total, curr, prev DATETIME;
DECLARE odd INT DEFAULT 1;
DECLARE done INT DEFAULT 0;
DECLARE c CURSOR FOR SELECT time FROM tbl;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN c;
read_loop: LOOP
FETCH c INTO curr;
IF odd=0 THEN
SET total=dateadd(total,datediff(curr,prev)); -- or something similar, I forget
END IF;
SET prev=curr;
SET odd=1-odd;
IF done THEN
LEAVE read_loop;
END IF;
END LOOP;
CLOSE c;
SELECT total;
END;