将mysql列从INT转换为TIMESTAMP

编程入门 行业动态 更新时间:2024-10-17 16:33:57
本文介绍了将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?

推荐答案

您快到了,使用 FROM_UNIXTIME() ,而不是直接复制该值.

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

本文发布于:2023-07-09 21:30:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1088262.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   mysql   INT   TIMESTAMP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!