计算MySQL中插入的第一行和最后一行之间经过的时间

发布于 2024-12-04 11:43:23 字数 1431 浏览 0 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若相惜即相离 2024-12-11 11:43:23
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
SELECT TIMEDIFF( MAX(time_col), MIN(time_col) ) FROM [tablename];

This will be helpful when it stores in time-sequentially. But timestamp column can be modified by updating, so I suggest the below query than above one.

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

You can use TIMESTAMPDIFF function either.

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
淡淡離愁欲言轉身 2024-12-11 11:43:23

这个例子是在 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);

this example is using mysql_* function in php,
you can replace to whatever method you are comfortable with

$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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文