PostgreSQL – Update Table with Data from Another Table

greatest-n-per-grouppostgispostgresqlupdate

I want to update the table car_check field fencing.(total 40 rows).I also use postgis function.
I think it's a little difficult.Any suggestions?

The code is the first carid example.

UPDATE car_check 
set fencing=ST_Contains
from (
SELECT ST_Contains(ST_AsText('01030000..'),
'POINT(23.912784 120.99178)') 
)as foo
where carid='AD-5487' and cargroupid='1'

enter image description here

Best Answer

Try this untangled version to update all rows of char_check:

UPDATE car_check c
SET    fencing = ST_Contains(u.geom, ST_MakePoint(t.lat::float8, t.lng::float8))
FROM   test t
      ,rule r
JOIN   (
   SELECT DISTINCT ON (polyname)
          polyname, geom
   FROM   unknown_table
   ORDER  BY polyname, version DESC
    ) u USING (polyname)
WHERE  t.id = c.carid
AND    r.cargroupid = c.cargroupid

Major points

  • Use the simpler ST_MakePoint to construct a point geometry from numeric input.

  • You do not need ST_AsText() at all, since your column geom is of type geometry already.

  • Fastest and simplest way to get the geometry for the biggest version per polyname in table unknown_table is to use DISTINCT ON, which is a Postgres extension of the SQL standard. More details in this related answer:
    How do I efficiently get "the most recent corresponding row"?

  • In reference to the currently accepted but invalid answer: the concatenation operator in Postgres (and standard SQL) is || (not +)