sql - pgAdmin/psql 如何将新列的数据导入现有记录?

标签 sql postgresql csv psql pgadmin

我的 PostgresQL 数据库中有几个包含用户记录的表。我想向用户表添加一个新列,并且想知道如何导入该新列的数据。

我有一个 CSV 文件,但无法找到在不覆盖任何现有记录的情况下导入数据的最佳方法。

提前致谢。

最佳答案

我认为您的请求不可能通过单个 psql 命令来实现,但我认为您可以通过几个步骤实现您想要的目标。

  1. 在数据库中创建与 CSV 结构匹配的临时表(我假设 CSV 包含 2 列、一个主键和新列数据)
  2. 使用 postgres' COPY 使用 CSV 数据填充此临时表命令
  3. 运行 UPDATE 查询将数据从临时表复制到现有表中
  4. DROP 临时表即可完成!

sqlfiddle example

DDL

-- existing table in your db
create table my_table (
  id integer PRIMARY KEY,
  some_col integer
);

-- some dummy data
insert into my_table (id, some_col)
values (1, 111), (2, 222), (3, 333);

-- create temp_table with same structure as CSV
create table temp_table (
  id integer PRIMARY KEY,
  new_col_val text
);

-- some dummy data, but you can use postgresql's COPY command to copy data from a CSV
-- docs: https://www.postgresql.org/docs/current/static/sql-copy.html
insert into temp_table (id, new_col_val)
values (1, 'hello'), (2, 'hi'), (3, 'hey');

查询

-- view initial contents of my_table
select * from my_table;

-- view initial contents of temp_table
select * from temp_table;

-- add new column to my_table
alter table my_table add column new_col text;

-- populate new column with data from temp_table
update my_table set new_col = new_col_val
from temp_table
where my_table.id = temp_table.id;

-- view results
select * from my_table;

关于sql - pgAdmin/psql 如何将新列的数据导入现有记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51393028/

相关文章:

sql - 从不同的数据库postgresql复制表

python - 在 CSV 文件中查找多次出现的对

javascript - 如何在 Angularjs 中将文件 json 导出为 CSV 或 XLSX 格式

sql - 如何在Mysql4.x中实现 "contains"函数?

c# - 如何使用 WPF 搜索数据库并将结果显示在 DataGrid 中

mysql concat 列作为字符串传递

sql - PARTITION BY Name, Id 来比较和检测问题

postgresql - 删除 PostgreSQL 8.3 上一组行中的重复字母

sql - 如何在 PostgreSQL 9.3 中对两列进行条件求和

php - 处理 CSV 文件中各个单元格中的换行符