Using MySQL's TIMESTAMP vs storing timestamps directly

两盒软妹~` 提交于 2019-11-27 06:27:40
Mchl

Arguments for TIMESTAMP

  • 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

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

The only real use for TIMESTAMP is when you want that field to be updated automatically when the row is updated (which is the default behaviour for that field), or when data storage requirements are so strict that 4 bytes per row really makes a difference to you.

Really the comparison should be between DATETIME and UNSIGNED INT, and I'd recommend DATETIME because:

  • You can use MySQL's native date/time functions for selecting by date ranges etc.
  • It is trivially easy to select these dates out as UNIX timestamps for easy formatting in PHP: SELECT UNIX_TIMESTAMP(field) FROM table, no need to select out the raw value and use strtotime
  • Easier to read and edit the fields in your database directly if you need to (as you pointed out).
  • No limitations on date range

Point two alone really removes any reason to store in integers, in my opinion.

This might not be a "scientific" answer but I always find the way MySql handles conversion, arithmetics, comparsion, etc... on TIMESTAMP columns confusing. An UNSIGNED INT column is much more straight forward and I always know what to expect.

P.S. Perhaps one other thing in favor of TIMESTAMP column is its ability to be automatically set to current time after each update or insert but that is not something you can't live without.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!