Home > Database > Mysql Tutorial > body text

MySQL中timestamp字段的一些规则

WBOY
Release: 2016-06-07 17:59:00
Original
1007 people have browsed it

有同学说timestamp字段的规则比较诡异。手册里面说的比较复杂,这里简单说明一下MySQL中 timestamp字段的一些规则。 分为两部分 定义规则: 1、 timestamp字段有三个属性: a) 是否允许NULL。默认为not null。 - b) 默认值 。可以设定为default CURRENT_TIMES

有同学说timestamp字段的规则比较“诡异”。手册里面说的比较复杂,这里简单说明一下MySQL中 timestamp字段的一些规则。

分为两部分

定义规则:

1、  timestamp字段有三个属性:

a)           是否允许NULL。默认为not null。
-


b)           默认值 。可以设定为default CURRENT_TIMESTAMP 或default 某个常量。若定义时缺省,对于第一个出现的timestamp字段,默认为CURRENT_TIMESTAMP, 对于其他timestamp字段,默认为 '0000-00-00 00:00:00'。 Default可以指定为null,前提是本字段允许null。

比如声明 field2 timestamp null default null。

c)           On update CURRENT_TIMESTAMP。是否在更新其他字段时自动将该timestamp字段修改为当前时间戳。对于第一个出现的timestamp字段,默认为On update CURRENT_TIMESTAMP, 对于其他timestamp字段,没有此行为。

2、  default CURRENT_TIMESTAMP 和 On update CURRENT_TIMESTAMP 可以同时修饰一个列。被这两个属性任意一个修饰的列定义为timestamps_with_niladic, 一个表中最多只能存在一个定义为timestamps_with_niladic的列。若超过1个,则建表失败。

以上是定义规则,用于定义建表行为。建表完成以后可以用show create table xxx 来验证上述规则。有了表定义后,我们来看timestamp的使用规则。

使用规则

1、 在insert或update语句中设置timestamp字段为null时

a) 若该列为not null,则设置为当前时间戳

b) 若该列为允许null, 则设置为null

2、在insert时若缺省,(insert 语句不指定该列的值),则等效于赋默认值。具体值由default部分决定。

3、若一个列有  On update CURRENT_TIMESTAMP 属性,修改本行其他列时会将此timestamp列的值修改为当前时间戳。

了解了上面的规则,再来分析你碰到的情况,看看是不是没那么”诡异“了
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!