【问题标题】:Insert bigint value into int column type Postgresql将 bigint 值插入 int 列类型 Postgresql
【发布时间】:2020-06-10 07:44:54
【问题描述】:

我需要在 Postgresql 中将一些数据从一个表插入到另一个表。我需要填充数据的表的架构如下所示:

create table public.test_int_table(
    id                          int,
    description             text,
    hash_code               int
);

问题是另一个表中的 id 列是 bigint 类型。因此,当我尝试将咬人数据插入 int 列时,我得到了一个异常:

insert into public.test_int_table
select * from public.test_table

SQL Error [22003]: ERROR: integer out of range

如何修剪 bigint 数据以在 Postgresql 中插入?通常的转换运算符似乎仅适用于向上转换(从 int 到 bigint 而不是其他)。 如果它不是一个不断增加的值,并且在大多数情况下它都适合 int ,所以我真的不在乎在这里失去精度。

【问题讨论】:

  • 为什么不创建int 列作为bigint 输入public.test_int_table 表?
  • 此表应保留一段时间,以免破坏兼容性。

标签: sql postgresql int bigint


【解决方案1】:

这可能非常危险,因为您可能会得到重复。但是您可以使用直接比较,然后处理太大的值。以下将它们“修剪”为NULL

insert into public.test_int_table (id, description, hash_code)
    select (case when id < 2^31 - 1 then id::int end) as id,
           description, hash_code
    from public.test_table;

请注意,这可能会完全弄乱数据。如果可以更改值,则可以替换为新值:

insert into public.test_int_table (id, description, hash_code)
    select dense_rank() over (order by id),
           description, hash_code
    from public.test_table;

【讨论】:

    猜你喜欢
    • 2016-02-03
    • 2021-03-04
    • 2020-06-11
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2015-11-05
    • 1970-01-01
    相关资源
    最近更新 更多