使用 MySQL 的 TIMESTAMP 与直接存储时间戳 [英] Using MySQL's TIMESTAMP vs storing timestamps directly

查看:10
本文介绍了使用 MySQL 的 TIMESTAMP 与直接存储时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以 MySQL 的 TIMESTAMP 格式与自定义 UNSIGNED INT 格式保存日期和时间值,我处于两难境地.这里的主要考虑因素是检索速度、PHP 中适当的范围计算以及偶尔格式化为人类可读值.

I'm in a dilemma about saving date and time values in MySQL's TIMESTAMP format vs in a custom UNSIGNED INT format. The main considerations here are speed of retrieval, appropriate range calculations in PHP and occasional formatting into human readable values.

每种类型所需的存储空间及其范围:

The storage space required for each type and their ranges:

DATETIME        8 bytes  '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
TIMESTAMP       4 bytes  '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC
UNSIGNED INT    4 bytes  (Maximum Value 4294967295)

我根本不需要 DATETIME 的范围.我在 TIMESTAMP 和 UNSIGNED INT 之间纠结.

I dont need the range of DATETIME at all. I'm torn between TIMESTAMP and UNSIGNED INT.

支持 UNSIGNED INT 的论据:

Arguments in favor of UNSIGNED INT:

  • 4294967295 的 UNIX 时间戳转换为 Sun,2106 年 2 月 7 日 06:28:15 GMT,这比 TIMESTAMP 还多,对我来说已经足够好了
  • 直接在 PHP 中比较这些时间戳会更快,而不是通过 strtotime() 转换 TIMESTAMP 然后比较它们

TIMESTAMP 给我的唯一优势是当我手动从 mysql 表中读取值并需要查看"它们时.

The only advantage TIMESTAMP would give me is when I'm reading in the values from the mysql table manually and need to 'see' them.

是否有任何令人信服的理由使用 TIMESTAMP 而不是 UNSIGNED INT?

Is there any compelling reason to use TIMESTAMP and not an UNSIGNED INT?

推荐答案

TIMESTAMP的参数

Arguments for TIMESTAMP

  • 它以 UTC 时区隐式存储数据.无论您的会话时区是什么.如果您需要使用不同的时区,这很有用.
  • 您可以使用 DEFAULT CURRENT_TIMESTAMPON UPDATE CURRENT_TIMESTAMP 自动设置时间戳列(在 MySQL 5.6.5 之前,每个表只有一列)
  • 您可以使用 datetime 函数进行日期比较、加法、减法、范围查找等,而无需使用 FROM_UNIXTIME() 函数 - 它可以更轻松地编写可以使用索引的查询
  • 在 PHP 中

  • It implicitly stores data in UTC time zone. No matter what your session time-zone is. Useful if you need to use different time zones.
  • You can have automated timestamping columns using DEFAULT CURRENT_TIMESTAMP or ON UPDATE CURRENT_TIMESTAMP (one column per table only until MySQL 5.6.5)
  • You can use datetime function for date comparison, addition, subtraction, range lookup etc, without the need to use FROM_UNIXTIME() function - it will make it easier to write queries that can use indexes
  • In PHP

>> date('Y-m-d h:i:s',4294967295);
'1969-12-31 11:59:59'

所以范围实际上是相同的

so the range is in fact the same

当 UNIX_TIMESTAMP() 用于 TIMESTAMP 列时,函数直接返回内部时间戳值,没有隐式字符串到 Unix 时间戳"的转换

When UNIX_TIMESTAMP() is used on a TIMESTAMP column, the function returns the internal timestamp value directly, with no implicit "string-to-Unix-timestamp" conversion

这篇关于使用 MySQL 的 TIMESTAMP 与直接存储时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆