MYSQL中怎么设置TIMESTAMP类型的默认值

30次阅读
没有评论

共计 2234 个字符,预计需要花费 6 分钟才能阅读完成。

这篇文章给大家介绍 MYSQL 中怎么设置 TIMESTAMP 类型的默认值,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

MYSQL 中 TIMESTAMP 类型可以设定默认值,就像其他类型一样。
1、自动 UPDATE 和 INSERT 到当前的时间:
表:
mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash;
Table  Create Table 
mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash;-
t1  CREATE TABLE `t1` (   
  `p_c` int(11) NOT NULL, 
  `p_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=gb2312   
数据:
1  2007-10-08 11:53:35
2  2007-10-08 11:54:00
insert into t1(p_c) select 3;
update t1 set p_c = 2 where p_c = 5;
数据:
1  2007-10-08 11:53:35
5  2007-10-08 12:00:37
3  2007-10-08 12:00:37
2、自动 INSERT 到当前时间,不过不自动 UPDATE。
表:
mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash;
Table  Create Table 
mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash;
t1  CREATE TABLE `t2` ( 
  `p_c` int(11) NOT NULL,   
  `p_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=gb2312 
数据:
insert into t2(p_c) select 4;
update t2 set p_c = 3 where p_c = 5;
1  2007-10-08 11:53:35
2  2007-10-08 12:00:37
5  2007-10-08 12:00:37
4  2007-10-08 12:05:19
3、一个表中不能有两个字段默认值是当前时间,否则就会出错。不过其他的可以。
表:
mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash;
Table  Create Table 
mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash; mdash;
t1  CREATE TABLE `t1` (   
  `p_c` int(11) NOT NULL, 
  `p_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 
  `p_timew2` timestamp NOT NULL DEFAULT 0000-00-00 00:00:00
  ) ENGINE=InnoDB DEFAULT CHARSET=gb2312 
数据:
1  2007-10-08 11:53:35  0000-00-00 00:00:00
2  2007-10-08 12:00:37  0000-00-00 00:00:00
3  2007-10-08 12:00:37  0000-00-00 00:00:00
4  2007-10-08 12:05:19  0000-00-00 00:00:00
TIMESTAMP 的变体
1,TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
在创建新记录和修改现有记录的时候都对这个数据列刷新
 
2,TIMESTAMP DEFAULT CURRENT_TIMESTAMP
在创建新记录的时候把这个字段设置为当前时间,但以后修改时,不再刷新它
 
3,TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
在创建新记录的时候把这个字段设置为 0,以后修改时刷新它
 
4,TIMESTAMP DEFAULT lsquo;yyyy-mm-dd hh:mm:ss rsquo;ON UPDATE CURRENT_TIMESTAMP
在创建新记录的时候把这个字段设置为给定值,以后修改时刷新它

关于 MYSQL 中怎么设置 TIMESTAMP 类型的默认值就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-08-03发表,共计2234字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)