简体   繁体   中英

Update from join returning id from other table in Postgres

I can't figure out how to do this in Postgres.

I have two tables, foo and bar :

foo :id, number

bar :id, foo_id

There is an entry in bar that corresponds to and entry in foo . I want to update foo and return the bar id when I do so. I though something like this would work, but I'm having a very difficult time getting join updates to work in Postgres.

I want to do something like this:

UPDATE 
    foo f 
INNER JOIN
    bar b 
ON 
    f.id = b.foo_id 
SET 
    f.number = 1 
RETURNING 
    b.id

Thanks.

Your syntax is off, try this instead:

UPDATE foo AS f
SET number = 1
FROM bar AS b
WHERE f.id = b.foo_id
RETURNING b.id

There are many references out there which could have shown you how to phrase an update join in Postgres, Stack Overflow being one of them .

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