如果冲突,请在更新前删除行

时间:2017-10-05 05:37:18

标签: sql postgresql

我有一个包含列的表:

  • microservice_id
  • transport_id
  • is_default
  • ...

和一个唯一键(microservice_id,transport_id) 我已经尝试了查询

UPDATE microservices_transports
SET
    transport_id = :next,
    username     = :username,
    password     = :password,
    is_default   = COUNT((SELECT *
                    FROM
                      (DELETE FROM microservices_transports AS mt WHERE mt.transport_id = :NEXT AND mt.microservice_id = microservice_id RETURNING *)
                    WHERE is_default = TRUE
                   )) > 0
WHERE
transport_id = :prev

主要思想是在更新之前删除所有冲突行,但DELETE子查询不能正常工作。我该如何解决?

  

[42601]错误:语法错误在或附近" FROM"

靠近DELETE

1 个答案:

答案 0 :(得分:0)

我会尝试重构声明:

数据:

t=# select * from a;
 i
---
 1
(1 row)
像你一样:

t=# begin; update a set i = (select count(*) from (delete from a returning *));
BEGIN
ERROR:  syntax error at or near "from"
LINE 1: update a set i = (select count(*) from (delete from a return...

重构:

t=# with d as (delete from a where i = 1 returning *)
, c as (select count(*) from d)
update a set i = c.count from c;
UPDATE 0