Mysql: Convert column from timestamp to int and perform conversion for each update

时光怂恿深爱的人放手 提交于 2021-02-10 15:47:02

问题


I have a existing database column of type timestamp that I need to modify to become an INT(11), but in order for this to happen I need to convert each timestamp value as I change it.

Here's my modify statement currently that won't correctly convert the timestamp:

ALTER TABLE my_table
MODIFY COLUMN updated_on INT(11) UNSIGNED NOT NULL;

Is there a way to provide a conversion function or something to the alter command? Otherwise I was thinking I could

  • Create a new column, called updated_on_temp of type INT(11) UNSIGNED NOT NULL
  • Convert and copy over all timestamps with:

UPDATE my_table
SET updated_on_temp = UNIX_TIMESTAMP(updated_on);

  • Delete the updated_on column
  • Rename updated_on_temp to updated_on

Is the second way the only efficient way to do this?


回答1:


This way doesn't require temp field to store timestamp type values, so should be more downtime friendly when altering on huge tables, and it's also avilable with DATE(TIME) type fields by removing UNIX_TIMESTAMP().

For convert int back to timestamp or datetime see: Converting mysql column from INT to TIMESTAMP

First we have to cast timestamp type to numeric datetime without punctuation (like 202102060020302), since numeric full form is too long for int to store, should alter field to bigint type:

ALTER TABLE `table` CHANGE `field` `field` BIGINT NOT NULL;

then cast int to numeric datetime and so on timestamp:

UPDATE `table` SET `field` = UNIX_TIMESTAMP(CAST(`field` AS DATETIME));

finally trim field type from bigint to int, if you don't care about 2038 year problem:

ALTER TABLE `table` CHANGE `field` `field` INT NOT NULL;

ref https://dev.mysql.com/doc/refman/8.0/en/date-and-time-type-conversion.html

> mysql> SELECT CURTIME(), CURTIME()+0, CURTIME(3)+0;
> +-----------+-------------+--------------+
> | CURTIME() | CURTIME()+0 | CURTIME(3)+0 |
> +-----------+-------------+--------------+
> | 09:28:00  |       92800 |    92800.887 |
> +-----------+-------------+--------------+
> mysql> SELECT NOW(), NOW()+0, NOW(3)+0;
> +---------------------+----------------+--------------------+
> | NOW()               | NOW()+0        | NOW(3)+0           |
> +---------------------+----------------+--------------------+
> | 2012-08-15 09:28:00 | 20120815092800 | 20120815092800.889 |
> +---------------------+----------------+--------------------+



回答2:


You can use the function

TIME_TO_SEC()

the converts time value to seconds



来源:https://stackoverflow.com/questions/45553079/mysql-convert-column-from-timestamp-to-int-and-perform-conversion-for-each-upda

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!