Mysql从两个日期开始经过的总时间

时间:2011-10-02 20:39:56

标签: mysql

如果我有两行

id created          start            stop
1  28-01-2011 23:00 28-01-2011 23:00 28-01-2011 23:01  
2  28-01-2011 23:10 28-01-2011 23:10 28-01-2011 23:11

我可以运行什么查询来获取一个日期的总耗用时间,因此对于28-01-2011,总时间为2分钟。

这可能吗?

1 个答案:

答案 0 :(得分:1)

一个选项很简单:

select sum(unix_timestamp(stop) - 
    unix_timestamp(start))/60 from table
    where date(created) = '28-01-2011';

mysql> select now(), date_add(now(), interval 10 minute);
+---------------------+-------------------------------------+
| now()               | date_add(now(), interval 10 minute) |
+---------------------+-------------------------------------+
| 2011-10-04 13:29:56 | 2011-10-04 13:39:56                 |
+---------------------+-------------------------------------+
1 row in set (0.01 sec)

mysql> select sum(unix_timestamp(now()) -
          unix_timestamp(date_add(now(), interval 10 minute)));
+----------------------------------------------------------------------------------+
| sum(unix_timestamp(now()) - unix_timestamp(date_add(now(), interval 10 minute))) |
+----------------------------------------------------------------------------------+
|                                                                             -600 |
+----------------------------------------------------------------------------------+
1 row in set (0.00 sec)


mysql> select sum(unix_timestamp(now()) - 
          unix_timestamp(date_add(now(), interval 10 minute))) / 60 ;
+---------------------------------------------------------------------------------------+
| sum(unix_timestamp(now()) - unix_timestamp(date_add(now(), interval 10 minute))) / 60 |
+---------------------------------------------------------------------------------------+
|                                                                              -10.0000 |
+---------------------------------------------------------------------------------------+
1 row in set (0.00 sec)