将mysql列从INT转换为TIMESTAMP [英] Converting mysql column from INT to TIMESTAMP

查看:480
本文介绍了将mysql列从INT转换为TIMESTAMP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我还很年轻,愚蠢没有什么经验时,我认为用PHP生成时间戳并将它们存储在MySQL innodb表的INT列中是一个好主意.现在,当该表具有数百万条记录并且需要一些基于日期的查询时,是时候将该列转换为TIMESTAMP了.我该怎么做?

When I was yound and stupid had little experiance, I decided it would be a good idea, to generate timestamps in PHP and store them in INT column in my MySQL innodb table. Now, when this table has millions of records and needs some date-based queries, it is time to convert this column to TIMESTAMP. How do I do this?

货币,我的桌子看起来像这样:

Currenlty, my table looks like this:

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

Here are the queries I came up with, to convert date_sent column to 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();

一切似乎对我来说都是正确的,但是当UPDATE pm SET date_sent2 = date_sent ;的时间到了时,我会收到警告,并且时间戳记值保持为空:

Everything seems correct to me, but when time comes for the UPDATEpmSETdate_sent2=date_sent;, I get a warning and timestamp value remains empty:

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

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

What am I doing wrong and is there a way to fix this?

推荐答案

您快到了,使用

You're nearly there, use FROM_UNIXTIME() instead of directly copying the value.

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

这篇关于将mysql列从INT转换为TIMESTAMP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆