簡體   English   中英

pgAdmin/psql 如何將新列的數據導入現有記錄?

[英]pgAdmin/psql how to import new column's data to existing records?

我在包含用戶記錄的 PostgresQL 數據庫中有幾個表。 我想向用戶表中添加一個新列,並且想知道如何導入該新列的數據。

我有一個 CSV 文件,但無法找到在不覆蓋任何現有記錄的情況下導入數據的最佳方法。

提前致謝。

我認為您的請求無法通過單個psql命令實現,但我認為您可以通過幾個步驟實現您的目標。

  1. 在您的數據庫中創建與 CSV 結構匹配的臨時表(我假設 CSV 包含 2 列、一個主鍵和新列數據)
  2. 使用 postgres 的COPY命令用 CSV 數據填充這個臨時表
  3. 運行UPDATE查詢以將數據從臨時表復制到現有表中
  4. DROP臨時表,你就完成了!

sqlfiddle 示例

數據線

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM