简体   繁体   English

Python PostgreSQL psycopg2将列连接到新列

[英]Python PostgreSQL psycopg2 concatenate columns to new column

I can concateante two columns using the following code: 我可以使用以下代码连接两列:

engine = create_engine(f'postgresql+psycopg2://user:password@host/db')
result = engine.execute('SELECT concat(col_1, col_2) AS uid FROM db_table;')

and I can alter the table to create a new column: 我可以更改表以创建新列:

engine.execute('ALTER TABLE db_table 
ADD COLUMN concat_1_2 VARCHAR NOT NULL;')

But how can I insert the result query into the table in an efficient way (very large number of rows)? 但是,如何高效地将结果查询插入表中(非常多的行)?

if you need only an insert you could use an insert select 如果只需要插入,则可以使用插入选择

insert into db_table (concat_1_2 )
SELECT concat(col_1, col_2) 
FROM db_table

otherwise just use an update 否则就使用更新

UPDATE db_table
SET  concat_1_2 = concat(col_1, col_2) 

If you want to replace columns col_1 and col_2 with new one col_1_2 , you can alter the table in this way: 如果要用新的col_1_2替换col_1col_2列,可以按以下方式更改表:

alter table db_table alter col_1 type varchar using concat(col_1, col_2);
alter table db_table rename col_1 to col_1_2;
alter table db_table drop col_2;

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

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