mysql - 将列类型从 int 或 bigint 更改为时间戳

标签 mysql postgresql

我目前有一个带有以毫秒为单位的时间戳的 bigint,我想更改为标准的“时间戳”列类型。

使用:

ALTER TABLE groupgps ALTER COLUMN date_stamp TYPE timestamp

我得到:

column "date_stamp" cannot be cast automatically to type timestamp without time zone

使用:

ALTER TABLE groupgps ALTER COLUMN date_stamp TYPE timestamp with time zone USING date_stamp::timestamp with time zone

我得到:

cannot cast type bigint to timestamp with time zone

除了从头开始重新制作表格之外,我真的不知所措,但我相信在删除表格之前我需要重新创建所有索引和引用该表​​格的任何内容。

最佳答案

ALTER ... USING 语句。

测试数据,来自您的样本。

CREATE TABLE groupgps AS
SELECT date_stamp::bigint
FROM generate_series(1,100) AS date_stamp;

使用to_timestamp()

看来您也可以使用to_timestamp 函数。 The docs pointing to to_timestamp声称这,

SELECT TIMESTAMP WITH TIME ZONE 'epoch' + 982384720.12 * INTERVAL '1 second';

The to_timestamp function encapsulates the above conversion.

所以我们也可以在 ALTER TABLE ... USING 中使用它,

ALTER TABLE groupgps
    ALTER COLUMN date_stamp SET DATA TYPE timestamp with time zone
    USING to_timestamp(date_stamp);

不使用to_timestamp()

然后我们改编来自 the docs 的例子.

ALTER TABLE groupgps
    ALTER COLUMN date_stamp SET DATA TYPE timestamp with time zone
    USING
        timestamp with time zone 'epoch' + date_stamp * interval '1 second';

关于mysql - 将列类型从 int 或 bigint 更改为时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41154546/

相关文章:

MySQL连接表只返回一个匹配项

php - 无需 super 权限更改MySQL时区

node.js - 使用 Sequelize 和 postgis 查找多边形中的点

python - psycopg2 "TypeError: not all arguments converted during string formatting"

postgresql - 如何在postgreSQL中加密我的密码?

postgresql - 如何在 CentOS 上运行 pg_ctlcluster?

PHP fputcsv 不从 SQL 查询输出第一行(输出第一行之后的所有其他行)

python - 如何将 MySQL timestamp(6) 读入 pandas?

mysql - 如何分别用他们的名字替换逗号分隔的部门 ID?

sql - 条件 "email ~* ' link1.com $'"是什么意思?