gpt4 book ai didi

mysql - MYSQL 中的自定义更新时间

转载 作者:行者123 更新时间:2023-11-29 07:06:49 25 4
gpt4 key购买 nike

我有一个包含一些行的表,其中有一个如下定义:

  `metric_update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

所以我真正想让它做的是在将数据插入该表时自动插入时间戳。确实如此。但我需要的是将基于 GMT 的时间写入该字段(当前服务器时间类似于 GMT+2)。

有没有办法让MYSQL做这样的事情?

最佳答案

如果你的服务器time and timezone settings配置正确,然后在内部 all times stored in TIMESTAMP columns are converted to GMT (因为这就是 Unix timestamp mandates )。当您检索此数据时,它们会转换回您的 session 时区。如果您希望它以 GMT 时区显示,您需要在检索数据时进行转换,而不是在插入数据时进行转换。

例如,请参阅下面的控制台转储。您可以自己运行这些命令进行检查。

mysql> use test;
Database changed
mysql> -- let's create a table we'll be working with
mysql> CREATE TABLE tsTable (
-> ID INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
-> ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-> );
Query OK, 0 rows affected (0.08 sec)

mysql> -- let's check current time as well as timezone settings
mysql> SELECT CURTIME(),@@global.time_zone, @@session.time_zone;
+-----------+--------------------+---------------------+
| CURTIME() | @@global.time_zone | @@session.time_zone |
+-----------+--------------------+---------------------+
| 16:25:51 | SYSTEM | +02:00 |
+-----------+--------------------+---------------------+
1 row in set (0.05 sec)

mysql> -- inserting empty row to table to trigger auto timestamp
mysql> INSERT INTO tsTable VALUES (null,null);
Query OK, 1 row affected (0.00 sec)

mysql> -- looks like the time in my local timezone is stored in table
mysql> SELECT * FROM tsTable;
+----+---------------------+
| ID | ts |
+----+---------------------+
| 1 | 2011-07-28 16:26:25 |
+----+---------------------+
1 row in set (0.00 sec)

mysql> -- switching to GMT
mysql> SET SESSION time_zone = '+0:00';
Query OK, 0 rows affected (0.00 sec)

mysql> -- check current time and timezone settings again
mysql> SELECT CURTIME(),@@global.time_zone, @@session.time_zone;
+-----------+--------------------+---------------------+
| CURTIME() | @@global.time_zone | @@session.time_zone |
+-----------+--------------------+---------------------+
| 14:27:53 | SYSTEM | +00:00 |
+-----------+--------------------+---------------------+
1 row in set (0.00 sec)

mysql> -- note: CURTIME() returns time two hours 'earlier' than before
mysql> -- let's see what's stored in the table again
mysql> SELECT * FROM tsTable;
+----+---------------------+
| ID | ts |
+----+---------------------+
| 1 | 2011-07-28 14:26:25 |
+----+---------------------+
1 row in set (0.00 sec)

mysql> -- TIMESTAMP is two hours 'earlier' than before too! Magick!

关于mysql - MYSQL 中的自定义更新时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6858493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com