Home > Database > Mysql Tutorial > body text

mysql中的datetime和timestamp_MySQL

WBOY
Release: 2016-06-01 13:45:53
Original
1217 people have browsed it

bitsCN.com

DATETIME:日期和时间的组合。支持的范围是'1000-01-01 00:00:00'到'9999-12-31 23:59:59'。MySQL以'YYYY-MM-DD HH:MM:SS'格式显示DATETIME值,但允许使用字符串或数字为DATETIME列分配值。
    TIMESTAMP[(M)]:时间戳。范围是'1970-01-01 00:00:00'到2037年。
TIMESTAMP列用于INSERT或UPDATE操作时记录日期和时间。如果你不分配一个值,表中的第一个TIMESTAMP列自动设置为最近操作的日期和时间。也可以通过分配一个NULL值,将TIMESTAMP列设置为当前的日期和时间。、
示例如下:
MYSQL中TIMESTAMP类型可以设定默认值,就像其他类型一样。
1、自动UPDATE 和INSERT 到当前的时间:
表:
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。
表:
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、一个表中不能有两个字段默认值是当前时间,否则就会出错。不过其他的可以。
表:
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值返回后显示为'YYYY-MM-DD HH:MM:SS'格式的字符串,显示宽度固定为19个字符。如果想要获得数字值,应在TIMESTAMP 列添加+0。

bitsCN.com
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