简体   繁体   中英

How to update one table and returning from related table in Postgres?

I have two table: users and stores. 'store' in users is a foreign key related to 'id' of stores.

select * from users;
id | username | store
1  | test     | NULL

select * from stores;
id | name

Now I try to update 'username' in users and return info of stores related to the id.

UPDATE
  users
SET
  username = 'something new'
FROM
  stores
WHERE
  users.id = 2 AND
  users.store = stores.id
RETURNING
  users.id,
  users.username,
  stores.id as "storeId",
  stores.name as "storeName"

It doesn't work, and the user cannot be found. It only works when no store in the query.

UPDATE
  users
SET
  username = 'something new'
WHERE
  users.id = 2
RETURNING
  users.id,
  users.username

What can I do if I want to store info returned by update query?

Just do the second update and use the store id in the users table:

with u as (
      update users
          set username = 'something new'
      where users.id = 2
      returning *
    )
select store
from u;

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