2012-02-03 12 views
10

Cuando yo era yound y estúpida tenido poco experiancia, decidí que sería una buena idea, para generar marcas de tiempo en PHP y almacenarlos en INT columna en mi tabla InnoDB de MySQL. Ahora, cuando esta tabla tiene millones de registros y necesita algunas consultas basadas en fechas, es hora de convertir esta columna a TIMESTAMP. ¿Cómo hago esto?conversión de columna MySQL de INT a TIMESTAMP

Currenlty, mi mesa tiene el siguiente aspecto:

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 

Estas son las preguntas que se me ocurrió, para convertir date_sent columna para 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(); 

Todo me parece correcto, pero cuando llega el momento de UPDATE pm SET date_sent2 = date_sent ;, recibo una advertencia y el valor de la marca de tiempo permanece vacío:

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

¿Qué estoy haciendo mal y hay una manera de arreglar esto?

Respuesta

28

Ya casi está allí, use FROM_UNIXTIME() en lugar de copiar directamente el valor.

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

Gracias. ¡Funciona perfectamente! –