何时使用datetime或timestamp [英] When to use datetime or timestamp

查看:125
本文介绍了何时使用datetime或timestamp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索过这个但没有明确的答案(特别是在后者)。在什么情况下您应该使用datetime或时间戳?

解决方案

假设您正在使用MS SQL Server ,请参阅下面的更新):


表只能有一个时间戳
列。每次包含时间戳列的行
插入或更新时,时间戳
列中的值都会更新。该属性
使时间戳列成为一个糟糕的
候选键,特别是主
键。对行
进行的任何更新都会更改时间戳值,从而
更改键值。如果列
位于主键中,则旧键值
不再有效,并且引用旧值的外键
不再有效。如果在动态游标中引用了
表,则所有
更新会更改游标中
行的位置。如果索引键中的列为
,则
数据行的所有更新也会生成
索引的更新。


有关 MSDN 的信息



如果您需要针对一行存储日期/时间信息,并且不具有该日期/时间更改,请使用DateTime;



另请注意: MS SQL Server时间戳记字段不是日期和时间,它们是相对序列的二进制表示当数据更改时。



更新






TIMESTAMP值从当前时区的
转换为UTC
存储的UTC,并从UTC
转换回当前时区为
检索。 (这仅适用于
TIMESTAMP数据类型,而不适用于其他
类型,例如DATETIME。)


MySQL参考的报价



更重要的是:


如果您存储一个TIMESTAMP值,而
则更改时区并检索
值,检索到的值为
,与您存储的值不同。


所以如果您在时区中使用应用程序,并需要日期/时间来反映个人用户的设置,使用时间戳。如果您需要一致性,无论时区如何,请使用Datetime


I've searched for this but no clear answers (especially on the latter). In what cases should you use a datetime or timestamp?

解决方案

Assuming you're using MS SQL Server (Which you're not, see the Update below):

A table can have only one timestamp column. The value in the timestamp column is updated every time a row containing a timestamp column is inserted or updated. This property makes a timestamp column a poor candidate for keys, especially primary keys. Any update made to the row changes the timestamp value, thereby changing the key value. If the column is in a primary key, the old key value is no longer valid, and foreign keys referencing the old value are no longer valid. If the table is referenced in a dynamic cursor, all updates change the position of the rows in the cursor. If the column is in an index key, all updates to the data row also generate updates of the index.

Information on MSDN

If you need to store date/time information against a row, and not have that date/time change, use DateTime; otherwise, use Timestamp.

Also Note: MS SQL Server timestamp fields are not Dates nor Times, they are binary representations of the relative sequence of when the data was changed.

Update

As you've updated to say MySQL:

TIMESTAMP values are converted from the current time zone to UTC for storage, and converted back from UTC to the current time zone for retrieval. (This occurs only for the TIMESTAMP data type, not for other types such as DATETIME.)

Quote from MySQL Reference

More notably:

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.

So if you are using an application across timezones, and need the date/time to reflect individual users settings, use Timestamp. If you need consistency regardless of timezone, use Datetime

这篇关于何时使用datetime或timestamp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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