MySQL日期函数datetime与timestamp的3大区别

作者:简简单单 2013-10-03

相同: 显示格式一致:YYYY-MM-DD HH:MM:SS;

不同:

范围: datetime支持的范围为’1000-01-01 00:00:00′到’9999-12-31 23:59:59′

TIMESTAMP值不能早于1970或晚于2037

储存:

TIMESTAMP

1.4个字节储存(Time stamp value is stored in 4 bytes)
2.值以UTC格式保存( it stores the number of milliseconds)
3.时区转化 ,存储时对当前的时区进行转换,检索时再转换回当前的时区。

timestamp列类型timestamp值可以从1970的某时的开始一直到2037年,精度为一秒,其值作为数字显示。

  timestamp值显示尺寸的格式如下表所示:
         +-------------------+------------------------+
     | 列类型       | 显示格式            |
     | timestamp(14) | yyyymmddhhmmss | 
     | timestamp(12) | yymmddhhmmss  |
     | timestamp(10) | yymmddhhmm    |
     | timestamp(8) | yyyymmdd            |
     | timestamp(6) | yymmdd          |
     | timestamp(4) | yymm            |
     | timestamp(2) | yy                |
     +-------------------+-------------------------+

  “完整”timestamp格式是14位,但timestamp列也可以用更短的显示尺寸创造

  最常见的显示尺寸是6、8、12、与14。

  你可以在创建表时指定一个任意的显示尺寸,但是定义列长为0或比14大均会被强制定义为列长14。

  列长在从1~13范围的奇数值尺寸均被强制为下一个更大的偶数。

  列如:

  定义字段长度   强制字段长度

  timestamp(0) -> timestamp(14)
  timestamp(15)-> timestamp(14)
  timestamp(1) -> timestamp(2)
  timestamp(5) -> timestamp(6)

  所有的timestamp列都有同样的存储大小,使用被指定的时期时间值的完整精度(14位)存储合法的值不考虑显示尺寸。

  不合法的日期,将会被强制为0存储


datetime

1.8个字节储存(8 bytes storage)
2.实际格式储存(Just stores what you have stored and retrieves the same thing which you have stored.)
3.与时区无关(It has nothing to deal with the TIMEZONE and Conversion.)

方法一:

 

你也可以:
select * from t1 where unix_timestamp(time1) > unix_timestamp('2011-03-03 17:39:05') and unix_timestamp(time1) < unix_
timestamp('2011-03-03 17:39:52');
就是用unix_timestamp函数,将字符型的时间,转成unix时间戳。个人觉得这样比较更踏实点儿。

 

方法二:

 

time1 between '2011-03-03 17:39:05' and '2011-03-03 17:39:52';

 

方法三:

可以讲datetime类型转换成date类型再进行比较
例如:convert(date,表名.datetime列名) >= convert(date,表名.datetime列名)

 

三种方法待求证,总之是不要用字符串这么直接比


默认值: TIMESTAMP 默认值不为空,可以设置为默认当前时间, NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
datetime 默认值可以设置为空

相关文章

精彩推荐