【问题标题】:Postgres alter column from time without time zone to intPostgres 将列从没有时区的时间更改为 int
【发布时间】:2011-08-31 04:24:01
【问题描述】:

我在将表列 TYPE 从没有时区的时间转换为整数时遇到问题。 那可能吗? 其中整数将等于秒。

我正在使用 ALTER table exampleTable ALTER COLUMN time TYPE integer。

【问题讨论】:

    标签: postgresql alter-table


    【解决方案1】:

    应该这样做:

     ALTER TABLE your_table 
         ALTER COLUMN time TYPE integer USING 0;
    

    ALTER COLUMN 通常仅在您希望保留该列中的数据时使用。在你的情况下,上面应该可以工作,但不会给你买任何东西。删除该列,然后添加一个类型为 integer 且默认值为 0 的新列同样有效。

    (顺便说一句:你不应该使用像time 这样的保留字作为列名)

    编辑
    如果您确实想转换现有数据,则可以使用:

     ALTER TABLE your_table 
         ALTER COLUMN time_column TYPE integer USING extract(epoch from time_column);
    

    【讨论】:

    • 谢谢!虽然我想保留旧数据,但我真的需要一个非常快速的解决方案。
    • 哦,我使用的“时间”关键字只是举例。再次感谢!
    【解决方案2】:

    跟进马的回答,你也可以在使用部分添加一个表达式,例如:

    ALTER TABLE your_table 
    ALTER COLUMN time TYPE integer USING (
      extract('hours' from time) * 3600 +
      extract('minutes' from time) * 60 +
      extract('seconds' from time)
    );
    

    http://www.postgresql.org/docs/current/static/sql-altertable.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-17
      • 2020-05-06
      • 2017-08-20
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 2016-12-03
      相关资源
      最近更新 更多