简体   繁体   English

从CSV有条件地插入postgres DB

[英]Conditional insert into postgres DB from CSV

I want to import a CSV into a Postgres table, but I want to be able to decide on the fly whether or not a column should be a 0 or a 1 depending on existing rows in the table. 我想将CSV导入Postgres表中,但是我希望能够根据表中的现有行即时确定列应为0还是1。

For example, I'm adding contacts to a table and want to mark them as primary if no contact exists already that is primary, otherwise add them as secondary: 例如,我正在将联系人添加到表中,并希望将其标记为主要联系人(如果不存在主要联系人),否则将其添加为次要联系人:

Existing rows: 现有行:

contact_id | branch_id | primary
-------------+-----------+--------
1          | 100       | 1
2          | 101       | 1
3          | 101       | 0

CSV data, CSV数据,

contact_id | branch_id
-----------+-----------
4          | 100
5          | 101
6          | 102
7          | 103

Desired result, 所需的结果,

contact_id | branch_id | primary
-----------+-----------+--------
1          | 100       | 1
2          | 101       | 1
3          | 101       | 0
4          | 100       | 0
5          | 101       | 0
6          | 102       | 1
7          | 103       | 1

Notice contact 4 and 5 gets added as secondary as primary contacts already exist for those branches, whereas 6 and 7 get added as primary as no primary contacts exist for those branches. 请注意,由于这些分支已经存在主要联系人,因此将联系人4和5添加为次要联系人,而由于这些分支不存在主要联系人,因此将6和7添加为主要联系人。

Is this possible with postgres 9.2? postgres 9.2有可能吗?

I would implement this in two stages using a PL/pgSQL function and a temporary table. 我将使用PL / pgSQL函数和一个临时表在两个阶段中实现它。 Basically: 基本上:

  1. create a temporary table with the columns corresponding to the CSV file 使用与CSV文件对应的列创建一个临时表
  2. COPY FROM your CSV file into that temp table COPY FROM CSV文件COPY FROM到该临时表中
  3. insert into the final table based on a SELECT from the temp table LEFT JOIN ed to existing rows in the final table, so you can ascertain whether a primary row already exists 根据从临时表LEFT JOIN到最终表中现有行的SELECT插入到最终表中,因此可以确定primary行是否已存在
  4. drop the temp table 删除临时表

(Incidentally, this means you can use a SECURITY DEFINER function, created as root , but run by a less privileged user, with the CSV filename hard-coded, rather than running the entire import as root .) (顺便说一句,这意味着您可以使用SECURITY DEFINER函数,该函数以root身份创建,但由特权较低的用户以CSV文件名硬编码运行,而不是以root身份运行整个导入。)

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

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