开发者

MySQL add timestamp values

I have a table in MySQL with this format: (time = timestamp on insert)

id |    tid |   uid |   time
31 |    1   |   14  |   2011-05-19 05:42:37   //start timestamp)
41 |    1开发者_JAVA百科   |   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)

What I need is to make a select that adds the time differences like this

(41 - 31) + (46 - 45) (i'm using the id's instead of the actual time values to better understand what I need to do )

something like SELECT (something that does this) AS TotalTimeSpent WHERE tid = '1'


If you insist on using this table layout (and I really hope you change your mind, it is truly horrific), you can do it with cursors in a stored procedure.

Pseudo-code would be something like this:

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜