简体   繁体   中英

Delete row before update if conflict

I have a table with columns:

  • microservice_id
  • transport_id
  • is_default
  • ...

and a unique key (microservice_id, transport_id) I've tried query

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

The main idea is to delete all conflict rows before update but DELETE subquery won't working. How can I fix it?

[42601] ERROR: syntax error at or near "FROM"

near DELETE

I would try to refactor the statement:

data:

t=# select * from a;
 i
---
 1
(1 row)

smth like your:

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...

refactored:

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

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