[英]How to replace values in a column in a table by condition in PostgreSQL?
I have a table named "building" in PostgreSQL.我在 PostgreSQL 中有一个名为“building”的表。 It has several columns and millions of rows.
它有几列和数百万行。 Each row has a unique id.
每一行都有一个唯一的 id。 It looks like
看起来像
id tags height building:levels area
1 apartment 58 m 17 109
2 apartment null null 111
3 shed 7 2 75sqm
4 greenhouse 6m 3 159
5 industrial 16 2;4 105
6 commercial 27 8 474
And I have another csv file with cleaned data for column height
and building:levels
.我还有另一个 csv 文件,其中包含列
height
和building:levels
的清理数据。 The csv looks like: csv 看起来像:
id height building:levels
1 58 17
3 7 2
4 6 3
5 16 4
6 27 8
I want to join the csv file back to the table on the server, and the final outcome might look like this:我想将 csv 文件加入到服务器上的表中,最终结果可能如下所示:
id tags height building:levels area
1 apartment 58 17 109
2 apartment null null 111
3 shed 7 2 75sqm
4 greenhouse 6 3 159
5 industrial 16 4 105
6 commercial 27 8 474
I want to replace the values in height
and building:levels
where the id
are the same in the table and the csv file.我想替换
height
和building:levels
表和 csv 文件中id
相同的级别。 I've tried to import data from csv but it didn't replace the values, only adding new rows.我尝试从 csv 导入数据,但它没有替换值,只是添加了新行。 How can I achieve this?
我怎样才能做到这一点?
You can import the csv file data in a temporary table first:可以先在临时表中导入csv文件数据:
CREATE TEMPORARY TABLE IF NOT EXISTS building_temp LIKE building ;
COPY building_temp (id, height, "building:levels") FROM your_csv_file.csv WITH options_list ;
See the manual for building the options_list.请参阅构建 options_list 的手册。
and then update the building table from that temporary table然后从该临时表更新构建表
UPDATE building AS b
SET height = bt.height
, "building:levels" = bt."building:levels"
FROM building_temp AS bt
WHERE b.id = bt.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.