2012-02-03 104 views
10

当我是yound和愚蠢的没有多少实验时,我决定用PHP生成时间戳并将它们存储在我的MySQL innodb表的INT列中将是个好主意。现在,当此表具有数百万条记录并需要一些基于日期的查询时,现在是将该列转换为TIMESTAMP的时候了。我该怎么做呢?将mysql列从INT转换为TIMESTAMP

Currenlty,我的表是这样的:

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_sentTIMESTAMP查询:

-- 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(); 

一切似乎是正确的我,但是当时间来到UPDATE pm SET date_sent2 = date_sent ;,我得到一个警告和时间戳值仍为空:

+---------+------+--------------------------------------------------+ 
| Level | Code | Message           | 
+---------+------+--------------------------------------------------+ 
| Warning | 1265 | Data truncated for column 'date_sent2' at row 1 | 

我在做什么错,有没有办法解决这个问题?

回答

28

您快到了,请使用FROM_UNIXTIME()而不是直接复制该值。

-- creating new column of TIMESTAMP type 
ALTER TABLE `pm` 
    ADD COLUMN `date_sent2` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP(); 

-- Use FROM_UNIXTIME() to convert from the INT timestamp to a proper datetime type 
-- assigning value from old INT column to it, in hope that it will be recognized as timestamp 
UPDATE `pm` SET `date_sent2` = FROM_UNIXTIME(`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(); 
+0

谢谢。完美的作品! – 2012-02-03 17:18:37