2012-02-03 35 views
10

Quando ero yound e stupida avuto poco experiance, ho deciso che sarebbe stata una buona idea, per generare timestamp in PHP e memorizzarli in INT colonna nella mia tabella di InnoDB MySQL. Ora, quando questa tabella ha milioni di record e richiede alcune query basate sulla data, è ora di convertire questa colonna in TIMESTAMP. Come faccio a fare questo?Conversione colonna mysql da INT a TIMESTAMP

currenlty, la mia tabella assomiglia a questo:

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 

Qui ci sono le domande che mi è venuta, per convertire date_sent colonna per 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(); 

Tutto sembra corretto per me, ma quando il tempo arriva per il UPDATE pm SET date_sent2 = date_sent ;, ricevo un avviso e il valore di timestamp rimane vuoto:

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

Cosa sto facendo di sbagliato e c'è un modo per risolvere questo problema?

risposta

28

Ci sei quasi, usa FROM_UNIXTIME() invece di copiare direttamente il valore.

-- 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

Grazie. Funziona perfettamente! –