考虑到数据库的效率,有必要把所有的时间datetime都设置为timestamp吗?

各种表从10行数据到100万行数据
虽然timestamp的缺点只支持到2035年,但是在这个缺点忽略不计的情况下,是否每个表都应该把datetime设置为timestamp呢?
从维护的角度考虑是否一些小表可以保留datetime呢

阅读 3.4k
1 个回答

你需要考虑到 timestamp 潜在的时区问题:

MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.) By default, the current time zone for each connection is the server's time. The time zone can be set on a per-connection basis. As long as the time zone setting remains constant, you get back the same value you store. If you store a TIMESTAMP value, and then change the time zone and retrieve the value, the retrieved value is different from the value you stored

根据 MySQL 官方文档, TIMESTAMP 在存入时, 会根据当前时区转换为 UTC 时间, 而在取出也会根据当前时区将 UTC 时间转换为 TIMESTAMP. 因此如果你的程序的时区有变化时, 那么写入和读出的 TIMESTAMP 就不一样了.

如果没有上面的时区的问题, 那么我觉得 TIMESTAMP 比较好一些.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进