简体   繁体   中英

Combine 2 update querys in a single query - performance

Im programming a favourite function.

For example we have multiple adresses and can choose one as favourite.

At the moment i got 2 querys to do this job:

UPDATE userdata
SET maindata = 0
WHERE 
cid = :id;

UPDATE userdata
SET maindata = 1
WHERE 
cid = :id AND id = :id2
LIMIT 1

In the first query i make all adresses as "no favourite" and in the second one i make the new choosen adress the favourite one.

Is there any way to imrpove this query or rewrite both into 1 ? Or even a better solution ?

If you want a single query you could use a case when (or an if)

update  userdata 
set maindate = case when id = :id2 then 1 
                else 0 end 
where  cid = :id;

for performance Be sure you have a proper index on userdata columns (cid, id)

and the number of rows scanned should be the same for the first wuary ..but in this way you avoid the second ..

eventually try create a composite index

 create index myidx1 on userdata(cid, id)
UPDATE userdata SET maindata = (case when cid = id AND id = id2 then 1 else 0 end);

This will help. I am not sure of your query but this will help. let me know if you looking something different...

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