计算在MySQL中插入的第一行和最后一行之间传递的时间

时间:2011-09-13 13:34:53

标签: php mysql timestamp innodb

在表格中,我有一个 timestamp 类型的字段。如何计算插入的第一行和最后一行之间经过的时间?

时间以这种方式存储: 2011-09-13 16:32:19

如果重要,该表使用InnoDB引擎!我将在PHP中执行此操作。

2 个答案:

答案 0 :(得分:2)

SELECT TIMEDIFF( MAX(time_col), MIN(time_col) ) FROM [tablename];

当按时间顺序存储时,这会很有用。但是时间戳列可以通过更新来修改,所以我建议以下查询而不是上面的查询。

SELECT TIMEDIFF( x.time_col, y.timecol ) FROM 
    ( SELECT time_col FROM [tablename] ORDER BY [primary_key] DESC LIMIT 1 ) x,
    ( SELECT time_col FROM [tablename] ORDER BY [primary_key] ASC  LIMIT 1 ) y

您也可以使用TIMESTAMPDIFF函数。

SELECT TIMESTAMPDIFF( SECOND, x.time_col, y.timecol ) FROM 
    ( SELECT time_col FROM [tablename] ORDER BY [primary_key] DESC LIMIT 1 ) x,
    ( SELECT time_col FROM [tablename] ORDER BY [primary_key] ASC  LIMIT 1 ) y

答案 1 :(得分:0)

这个例子在php中使用mysql_ *函数,
你可以用你喜欢的任何方法替换

$con = mysql_connect(...); // your connection
$sql = <<<SQL
select 
  max(the_field) as last_time ,
  min(the_field) as first_time,
  timestampdiff(second, min(the_field), max(the_field)) as diff_time
from your_table
SQL;
$res = mysql_query($sql, $con);
$row = mysql_fetch_assoc($res);
mysql_free_result($res);