Postgres - 如何使用外键批量插入 table

Postgres - how to bulk insert table with foreign keys

我想对我的 postgreSQL 数据库进行批量插入。

我有一个临时暂存区table,我批量插入了数据

TABLE public.temp_inverter_location
(
    id integer ,
    inverter_num_in_sld integer,
    lift_requirements character varying,
    geo_location_id integer NOT NULL (foreign key references geo_location.id),
    location_name character varying,
    project_info_id integer NOT NULL (foreign key references project_info.id)
 )

我正在尝试填充两个外键列 temp_inverter_location.geo_location_idtemp_inverter_location.project_info_id

引用的两个 table 由它们的 id 列引用:

geo_location

CREATE TABLE public.geo_location

    (
        id integer,
        country character varying(50) COLLATE pg_catalog."default",
        region character varying(50) COLLATE pg_catalog."default",
        city character varying(100) COLLATE pg_catalog."default",
        location_name character varying COLLATE pg_catalog."default",

    )

project_info

CREATE TABLE public.project_info
(
    id integer 
    operation_name character varying,
    project_num character varying(10),
    grafana_site_num character varying(10)
)

我想将正确的外键填充到 temp_inverter_location.geo_location_idtemp_inverter_location.project_info_id 列中。

我正在尝试使用 INSERT INTO SELECT 填充 temp_inverter_location.geo_location_id 与匹配 geo_location.location_nametemp_inverter_location.name.

JOIN

我试过这个查询,但是 inverter_location.geo_location_id 仍然是空白:

INSERT INTO temp_inverter_location(geo_location_id) SELECT geo_location.id FROM geo_location INNER JOIN temp_inverter_location ON geo_location.location_name=temp_inverter_location.location_name;

如果需要更多信息,请告诉我,谢谢!

我能够使用 update 引用另一个 table 来解决这个问题。

基本上,我使用

更新了 geo_location_id 列
 UPDATE temp_inverter_location SET geo_location_id = geo_location.id FROM geo_location WHERE geo_location.location_name = temp_inverter_location.location_name;

并使用

更新了project_info_id
UPDATE load_table SET project_info_id = project_info.id FROM project_info WHERE project_info.operation_name = load_table.location_name;

好像有用。