【问题标题】:Migrating data from old table to new table Postgres with extra column使用额外的列将数据从旧表迁移到新表 Postgres
【发布时间】:2020-10-03 10:24:00
【问题描述】:

表结构:

旧表结构:

新表结构:

查询:

INSERT INTO hotel (id, name, hotel_type, active, parent_hotel_id)
SELECT id, name, hotel_type, active, parent_hotel_id 
FROM dblink('demopostgres', 'SELECT id, name, hotel_type, active, parent_hotel_id FROM hotel')
    AS data(id bigint, name character varying, hotel_type character varying, active boolean, parent_hotel_id bigint);

出现以下错误:

错误:“created_by”列中的空值违反非空约束 详细信息:失败行包含 (1, Test Hotel, THREE_STAR, t, null, 空,空,空,空,空)。 SQL状态:23502

我尝试插入其他必需的列

注意:created_by 为 Jsonb

created_by = '{
    "id": 1,
    "email": "tes@localhost",
    "login": "test",
    "lastName": "Test",
    "firstName": "Test",
    "displayName": "test"
}'
created_date = '2020-02-22 16:09:08.346'

如何在从旧表中移动数据时传递 created_by 和 created_date 列的默认值?

【问题讨论】:

  • 创建新表时定义默认值。
  • 表已经创建,我正在将数据从旧表移动到新表,现在我想传递两列(created_by,created_date)的默认值,其余部分来自旧表(见上面的查询)

标签: sql json postgresql


【解决方案1】:

有多种选择。

首先,INSERT 失败,因为该字段不是 NULL。您可以 ALTER TABLE(https://www.postgresql.org/docs/12/sql-altertable.html)as 取消设置导入,使用值更新字段并重置 NOT NULL。

ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL

两个,正如@XraySensei 所说,您可以使用 ALTER TABLE 将 DEFAULT 值添加到表中:

ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]
    action [, ... ]
ALTER [ COLUMN ] column_name SET DEFAULT expression

第三个选项是将默认值嵌入到查询中:

create table orig_test(id integer NOT NULL, fld_1 varchar, fld_2 integer NOT NULL);

insert into orig_test(id, fld_1, fld_2) values (1, 'test', 4);
insert into orig_test(id, fld_1, fld_2) values (2, 'test', 7);

insert into default_test (id, fld_1, fld_2) select id, fld_1, fld_2 from orig_test ;
ERROR:  null value in column "fld_3" violates not-null constraint
DETAIL:  Failing row contains (1, test, 4, null).

insert into default_test (id, fld_1, fld_2, fld_3) select id, fld_1, fld_2, '06/14/2020' AS fld_3 from orig_test ;
INSERT 0 2


【讨论】:

    猜你喜欢
    • 2016-07-23
    • 2013-12-26
    • 2017-12-11
    • 2017-12-11
    • 2013-05-03
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    相关资源
    最近更新 更多