更新更新?

时间:2018-01-02 19:49:34

标签: sql postgresql

有没有办法做SELECT ... FOR UPDATE但是嵌套更新返回而不是选择?我想的场景看起来有点像:

UPDATE cars
SET model='myModel', ownerID=(
  UPDATE owners
  SET cars_owned = cars_owned + 1
  WHERE name = 'fred'
  RETURNING id
)
WHERE id = 'abc123';

有没有办法在没有交易的情况下原子地做到这一点?

1 个答案:

答案 0 :(得分:2)

排序。您可以使用CTE:

WITH o as (
      UPDATE owners
          SET cars_owned = cars_owned + 1
      WHERE name = 'fred'
      RETURNING id
     )
UPDATE cars
    SET model = 'myModel',
        ownerID = (SELECT id FROM o);
WHERE id = 'abc123';