I have a table named "building" in PostgreSQL. It has several columns and millions of rows. Each row has a unique 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
. The csv looks like:
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:
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. I've tried to import data from csv but it didn't replace the values, only adding new rows. How can I achieve this?
CodePudding user response:
You can import the csv file data in a temporary table first :
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.
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