【问题标题】:Postgres CREATE TABLE AS SELECT with unknown column typePostgres CREATE TABLE AS SELECT 列类型未知
【发布时间】:2013-12-27 18:27:40
【问题描述】:

我想用以下查询创建一个表:

create table something as
select 
      other_id, 
      other_title, 
      '0.0.0.0' as IP, 
      1 as used 
from
      other_table

但 Postgres 抱怨说:

column "ip" has type "unknown"

如何将其指定为char 类型?

【问题讨论】:

    标签: postgresql types casting create-table


    【解决方案1】:

    您需要显式转换您的列,如下所示:

    '0.0.0.0'::INET as IP,
    

    【讨论】:

    • 或者 ::text 如果您不想将其作为真实 IP 处理
    【解决方案2】:

    你应该指定类型,使用 '0.0.0.0'::text AS IP

    【讨论】:

      【解决方案3】:

      至少从 Postgres 9.4 开始,这不会引发 EXCEPTION,而只会引发 WARNING。无论如何都会创建该表,如果没有为字符串文字指定类型,则使用数据类型为 unknown 的列:

      第 9.4 页的 dbfiddle here

      Postgres 10 引入了更有用的默认行为。除非显式转换,否则字符串文字将转换为默认数据类型 text。所以你不会再得到unknown 类型的列了:

      dbfiddle here

      this commit介绍(附详细说明)。

      现在unknown 类型已被标记为伪类型。 Details in this commit.

      【讨论】:

        猜你喜欢
        • 2020-11-27
        • 2013-06-29
        • 2010-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多