繁体   English   中英

使用额外的列将数据从旧表迁移到新表 Postgres

[英]Migrating data from old table to new table Postgres with extra column

表结构:

旧表结构:

旧表结构

新表结构:

在此处输入图像描述

询问:

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);

出现以下错误:

ERROR: null value in column "created_by" violates not-null constraint DETAIL: Failing row contains (1, Test Hotel, THREE_STAR, t, null, null, null, null, null, null). SQL state: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 列的默认值?

有几种选择。

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

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


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM