将数据从CSV文件导入SQL表并考虑外键

时间:2017-03-17 21:58:04

标签: sql postgresql

当我必须考虑将信息导入到的表与数据库中已存在的表之间的外键关系时,如何从CSV文件将数据导入SQL表?

我有两张桌子:

CREATE TABLE project_info (
    project_id SERIAL PRIMARY KEY;
    project_accountnum int,
    name text
);

CREATE TABLE project_forecast  (
    forecast_id SERIAL PRIMARY KEY,
    project_id int REFERENCES project_info (project_id),
    forecast_amount int
);

我有一个CSV文件,其中包含项目名称及其各自的预测。将项目名称放在project_forecast表中是多余的,因为它始终是相同的 - 因此是外键引用。但是,我想使用COPY FROM功能上传CSV,但如何考虑外键呢? CSV应该采用不同的格式吗?它应该有其他列吗?

1 个答案:

答案 0 :(得分:0)

评论太长了。

我的建议是copy进入临时表。然后,您可以从登台表加载最终表。查询看起来像这样:

with i as (
      insert into project_info(projectname)
          select distinct projectname
          from project_forecast_staging
          returning *
     ),
insert into project_forecast (project_id, forecast_amount)
    select i.project_id, pfs.forecast_amount
    from project_forecast_staging pfs join
         i
         on pfs.projectname = i.projectname;

(如果您有其他列或其他注意事项,这可能会过于简单。)