简体   繁体   English

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

[英]Importing data into a SQL table from a CSV file and considering foreign keys

How do I import data into a SQL table from a CSV file when I have to consider foreign key relationships between the table I am importing information to, and an already existing table in the database? 当我必须考虑将信息导入到的表与数据库中已存在的表之间的外键关系时,如何从CSV文件将数据导入SQL表?

I have two tables: 我有两张桌子:

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

I have a CSV file that contains the project names and their respective forecasts. 我有一个CSV文件,其中包含项目名称及其各自的预测。 It would be redundant to have the project names in the project_forecast table as it would always be the same--hence the foreign key reference. 将项目名称放在project_forecast表中是多余的,因为它始终是相同的 - 因此是外键引用。 However, I want to upload the CSV using the COPY FROM function but how do I take in account the foreign keys? 但是,我想使用COPY FROM功能上传CSV,但如何考虑外键呢? Should the CSV be in a different format? CSV应该采用不同的格式吗? Should it have additional columns? 它应该有额外的列吗?

This is too long for a comment. 这个评论太长了。

My recommendation is to copy into a staging table. 我的建议是copy到临时表中。 Then you can load the final table from the staging table. 然后,您可以从登台表加载最终表。 The query looks something like this: 查询看起来像这样:

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;

(This is perhaps oversimplified if you have additional columns or other considerations.) (如果您有其他列或其他注意事项,这可能会过于简单。)

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

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