mysql timestamp 转换 int,将mysql列从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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值