I have one two tables in postgis. one is Bank which is point and another is IndiaState which is polygon. Both of the tables are having a column named State. For Bank state column is empty and IndiaState table the state column is having name of the state. I want to populate the state column in Bank table by using ST_Intersects. I am able to select the Bank points falling under a particular state
select ST_Intersection("IndiaState".geom, TN_Bank.geom) as inter
"Bank_Name", "Lat"
from "IndiaState" INNER JOIN TN_Bank ON ST_Intersects("IndiaState".geom, TN_Bank.geom)
where "IndiaState".state='KERALA'
The above sql is returning 66 rows which is correct.
But the update command is not working properly
update TN_Bank set "State"='KERALA' from
(select ST_Intersection("IndiaState".geom, TN_Bank.geom) as inter
"Bank_Name", "Lat"
from "IndiaState" INNER JOIN TN_Bank ON ST_Intersects("IndiaState".geom, TN_Bank.geom)
where "IndiaState".state='KERALA')x
It is updating all of the rows in Bank table. Kindly help.
UPDATE TN_Bank dst
SET "State" = 'KERALA'
FROM "IndiaState" src
WHERE ST_Intersects(src.geom, dst.geom)
AND src.state = 'KERALA'
;
Since you are not using any fields from the source table (and more than one row could satisfy the intersects()), you can move the src table to an exists() check:
UPDATE TN_Bank dst
SET "State" = 'KERALA'
WHERE EXISTS (
SELECT *
FROM "IndiaState" src
WHERE src.state = 'KERALA'
AND ST_Intersects(src.geom, dst.geom)
);