简体   繁体   English

MySQL DATETIME的UNIX时间戳

[英]UNIX Timestamp to MySQL DATETIME

I have a table with statistics and a field named time with Unix Timestamps. 我有一个包含统计信息的表和一个名为time with Unix Timestamps的字段。

There are about 200 rows in the table, but I would like to change the Unix timestamps to MySQL DATETIME without losing the current rows. 表中有大约200行,但我想将Unix时间戳更改为MySQL DATETIME而不会丢失当前行。 The current table: 目前的表格:

CREATE TABLE `stats` (
    `id` int(11) unsigned NOT NULL auto_increment,
    `time` int(11) NOT NULL,
    `domain` varchar(40) NOT NULL,
    `ip` varchar(20) NOT NULL,
    `user_agent` varchar(255) NOT NULL,
    `domain_id` int(11) NOT NULL,
    PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

So the time (INT) should be a DATETIME field. 所以time (INT)应该是DATETIME字段。

How can I update the Unix Timestamp to MySQL's DATETIME? 如何将Unix时间戳更新为MySQL的DATETIME?

Remember to test it before using it for real, this is written from memory but should give you a good idea. 记得在真正使用它之前测试它,这是从内存中写的,但应该给你一个好主意。

ALTER TABLE `stats` CHANGE `time` `unix_time` int(11) NOT NULL // rename the old column
ALTER TABLE `stats` ADD `time` DATETIME NOT NULL // create the datetime column
UPDATE `stats` SET `time`=FROM_UNIXTIME(unix_time) // convert the data
ALTER TABLE `stats` DROP `unix_time` // drop the old unix time column
  1. use alter table to create a new column (eg. time2) with the datetime type in the same table 使用alter table在同一个表中创建一个具有datetime类型的新列(例如,time2)
  2. update stats set time2=from_unixtime(time); update stats set time2 = from_unixtime(time);
  3. use alter table to a) delete the time column, and b) rename the time2 to time. 使用alter table来a)删除时间列,b)将time2重命名为time。
ALTER TABLE `stats`
MODIFY COLUMN `time` timestamp NULL DEFAULT '0000-00-00 00:00:00' AFTER `id`;
ALTER TABLE `stats`
MODIFY COLUMN `time` datetime NULL DEFAULT '0000-00-00 00:00:00' AFTER `id`;

Here's a PDO example of how to use FROM_UNIXTIME in a prepared statement: 这是一个如何在准备语句中使用FROM_UNIXTIME的PDO示例:

$query = "INSERT INTO " .$this->table_name.  " SET origTS=FROM_UNIXTIME(:d2)";                
$stmt = $this->conn->prepare($query);
$stmt->bindParam(":d2", $this->origTS);         // UNIX time [ but seconds! ] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM