如何更新一个表并从Postgres中的相关表返回?

时间:2018-03-06 14:43:53

标签: sql postgresql

我有两个表:用户和商店。 '存储'在用户中是与' id'相关的外键。商店。

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

select * from stores;
id | name

现在我尝试更新用户名'在用户和返回与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"

它无法正常工作,无法找到用户。它仅在查询中没有商店时才有效。

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

如果我想存储更新查询返回的信息,我该怎么办?

1 个答案:

答案 0 :(得分:1)

只需执行第二次更新并使用users表中的商店ID:

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