2012-02-03 113 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