【问题标题】:How can I insert union tables to table in PostgreSQL?如何将联合表插入 PostgreSQL 中的表?
【发布时间】:2022-01-02 07:36:28
【问题描述】:

我有这个查询并将行插入到 MYSQl 数据库中并且工作完美。

insert int test(id,user)
select null,user from table2
union 
select null,user from table3

但是当在 PostgreSQL 中运行上述查询时不起作用。我得到这个错误column "id" is of type integer but expression is of type text,但是当我运行下面的两个查询时,如下所示。

当我在 PostgreSQL 中运行以下查询时,它可以正常工作:

insert into test(id,user)
select null,user from table2

或者在 PostgreSQL 的下面查询它可以正常工作:

insert int test(id,user)
select null,user from table3

或者在 PostgreSQL 的下面查询它可以正常工作:

select null,user from table2
union 
select null,user from table3

【问题讨论】:

    标签: postgresql union sql-insert


    【解决方案1】:

    null 不是实数值,因此没有数据类型。默认假定数据类型是text,这就是错误消息的来源。只需在第一个 SELECT 中将值转换为 int

    insert into test(id, "user")
    select null::int, "user" from table2
    union 
    select null, "user" from table3
    

    或者更好的是,完全省略id,以便使用为id 列定义的任何默认值。尝试将null 插入名为id 的列中听起来很奇怪

    insert into test("user")
    select "user" from table2
    union 
    select "user" from table3
    

    请注意,user 是保留关键字和内置函数,因此您必须引用它以避免出现问题。从长远来看,我建议为该列找到一个不同的名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 2020-08-05
      • 2016-12-17
      • 2023-04-04
      • 2017-06-04
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多