【发布时间】:2012-02-26 07:05:59
【问题描述】:
当我年轻的时候,stupid 没有什么经验,我决定用 PHP 生成时间戳并将它们存储在我的 MySQL innodb 表的INT 列中是个好主意。现在,当这个表有数百万条记录并且需要一些基于日期的查询时,是时候将该列转换为TIMESTAMP。我该怎么做?
当前,我的表是这样的:
id (INT) | message (TEXT) | date_sent (INT)
---------------------------------------------
1 | hello? | 1328287526
2 | how are you? | 1328287456
3 | shut up | 1328234234
4 | ok | 1328678978
5 | are you... | 1328345324
这是我想出的查询,将date_sent 列转换为TIMESTAMP:
-- creating new column of TIMESTAMP type
ALTER TABLE `pm`
ADD COLUMN `date_sent2` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP();
-- assigning value from old INT column to it, in hope that it will be recognized as timestamp
UPDATE `pm` SET `date_sent2` = `date_sent`;
-- dropping the old INT column
ALTER TABLE `pm` DROP COLUMN `date_sent`;
-- changing the name of the column
ALTER TABLE `pm` CHANGE `date_sent2` `date_sent` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP();
对我来说一切似乎都是正确的,但是当UPDATEpmSETdate_sent2=date_sent; 的时间到了,我收到一个警告并且时间戳值仍然为空:
+---------+------+--------------------------------------------------+
| Level | Code | Message |
+---------+------+--------------------------------------------------+
| Warning | 1265 | Data truncated for column 'date_sent2' at row 1 |
我做错了什么,有办法解决这个问题吗?
【问题讨论】: