简体   繁体   中英

How to update a table in postgis using ST_Intersects

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.

  • you don't have to specify the target table in the FROM clause, it is already in the range table
  • you need to link/associate the target table to the source-table(s), I moved your ON() clause to the WHERE clause

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)
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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