如何使用匹配值使用 CSV 文件中的数据更新 Postgres 中的列

UWG*_*OSE 1 sql postgresql sql-update

我在 Postgresql 数据库中有一个表,其中包含列nameemail,该name列已填充​​,但该email列为空。我还有一个 CSV 文件,其中包含列useruser_email已填充。如何email使用 CSV 文件更新列以匹配 和user以及name更新正确emailuser_email

我一直在寻找答案或浏览一些教程,但我不太确定如何表达问题,所以我无法找到任何答案。

这就是我的 Postgres 表现在的样子:

| name     | email    |
| joh      |          |
| alex     |          |
| adams    |          |
Run Code Online (Sandbox Code Playgroud)

这是我的 CSV 文件:

| user     | user_eamil|
| joh      | a@g.com  |
| alex     | a@g.com  |
| adams    | a@g.com  |
Run Code Online (Sandbox Code Playgroud)

小智 7

您需要创建一个中间表(也称为“临时表”)。

然后将 CSV 文件导入到该表中。之后,您可以从导入的数据更新目标表:

update target_table
   set email = t.user_eamil
from staging_table st
where st."user" = target_table.name;
Run Code Online (Sandbox Code Playgroud)

这假设name在您的目标表中是唯一的,并且每个用户在输入文件中只出现一次。