8

I have a database with sites and counties. Every site is located in one county. In the sites table, the county is already mentioned but I want to replace it with the ID, which in is the other table.

My update code is as follows:

UPDATE sites
SET cgid = c.gid 
FROM (select c.gid as a from counties c
INNER JOIN sites s
ON c.name = s.county) p;

The table sites is updated, although every value in the cgid column is the same (the ID of the first county). What can I do to get the right values?

Toik95
  • 157
  • 1
  • 2
  • 13
  • What do you mean with "whole array"? is your `cgid` column an `array`? Or the `name` or `county` columns? –  Nov 02 '16 at 11:18

3 Answers3

14

The target table of an update statement should never be repeated in the from clause

So I think you want this:

UPDATE sites s
  SET cgid = c.gid 
FROM counties c 
where c.name = s.county;

This assumes that counties.name and sites.county are both unique.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0
UPDATE sites AS s
SET cgid = c.gid
FROM counties AS c
WHERE c.name = s.county
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You don't need a JOIN. Instead, you just need to connect the two tables in the WHERE clause:

UPDATE sites s
    SET cgid = c.gid 
    FROM counties c
    WHERE c.name = s.county;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786