如何在MySQL中最有效地获取两个日期时间值之间的unix时间戳间隔?
这种方式肯定有效,但它调用 UNIX_TIMESTAMP 2 次:
mysql> select UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP('2009-09-23 22:07:42');
+---------------------------------------------------------------+
| UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP('2009-09-23 22:07:42') |
+---------------------------------------------------------------+
| 639 |
+---------------------------------------------------------------+
1 row in set (0.05 sec)
This way surely works,but it calls UNIX_TIMESTAMP 2 times:
mysql> select UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP('2009-09-23 22:07:42');
+---------------------------------------------------------------+
| UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP('2009-09-23 22:07:42') |
+---------------------------------------------------------------+
| 639 |
+---------------------------------------------------------------+
1 row in set (0.05 sec)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
难道不应该
只对一个函数调用执行相同的操作(不包括
now()
)吗? (目前无法访问 MySQL,MSSQL 的工作方式略有不同,因此无法测试)。基本上,UNIX 时间戳是自某个奇怪纪元以来的秒数,因此差异只是秒数的差异。另外,该功能仅在 MySQL 5 及更高版本中可用。
但总的来说,当出现问题时要担心性能,在此之前编写可读的代码。
Shouldn't
do the same with just one function call (not counting
now()
)? (No access to MySQL right now and MSSQL works a little different, so can't test).Basically a UNIX timestamp is the number of seconds since a weird epoch, so a difference is just a difference in seconds. Also, this function is only available in MySQL 5 and later.
But in general, worry about performance when you have a problem, write readable code until then.