I have 2 postgres tables like below
table 1
A,table2_id,C
1,2,3
4,5,6
7,5,8
table 2
ID, name
2,'cat'
5,'dog'
9,'fish'
I need to replace id of dog with the id of fish inside table1 column table2_id.
At the end, table 1 should be updated like below where 2nd and 3rd rows of column table2_id should be updated with the IDs of fish from table2
table 1
A,table2_id,C
1,2,3
4,9,6
7,9,8
I wrote a query but it’s not updating any records in table1. What’s wrong with my query?
UPDATE table1
SET table2_id = table2_updated.id
FROM table2 AS table2_updated
WHERE table1.table2_id = table2_updated.id AND table2_updated.name = 'fish';
2
Answers
Not sure what you were doing in the query but this should do it for you.
You do an INNER JOIN and as I put below you can select from the query before doing the update this way to see what would be updated (just for validation, that line is commented out), and then run the update like this.
See example. Direct update
Update thru name
Condition
table1.table2_id = table2_updated.id
is wrong or insufficient.You can take as source
name=’dog’->id=5 — > name=’fish’->Id=9