[英]In an existing table with records, how do I create a new datetime2(2) column and populate it with values based on another column?
[英]pgAdmin/psql how to import new column's data to existing records?
我在包含用户记录的 PostgresQL 数据库中有几个表。 我想向用户表中添加一个新列,并且想知道如何导入该新列的数据。
我有一个 CSV 文件,但无法找到在不覆盖任何现有记录的情况下导入数据的最佳方法。
提前致谢。
我认为您的请求无法通过单个psql
命令实现,但我认为您可以通过几个步骤实现您的目标。
COPY
命令用 CSV 数据填充这个临时表UPDATE
查询以将数据从临时表复制到现有表中DROP
临时表,你就完成了!数据线
-- 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.