简体   繁体   中英

Combine two queries into one in same table (same columns/different rows)

For a messaging system, I'm trying to mark the appropriate to_del and from_del fields for employee 2.

Here is before employee 2 deletes messages:

company_id | to | from | to_del | from_del
    1        4     2       0         0
    1        2     4       0         0

Here is after employee 2 deletes messages:

company_id | to | from | to_del | from_del
    1        4     2       0         1
    1        2     4       1         0

I have to run 2 queries for this to work:

UPDATE messages SET from_del='1' WHERE company_id=1 AND from=2
UPDATE messages SET to_del='1' WHERE company_id=1 AND to=2

Is there anyway to merge these 2 queries into 1 more efficient query? Something like:

UPDATE messages SET from_del='1',to_del='1' WHERE company_id=1 AND (from=2 OR to=2)

This single query's issue is that it marks all 4 delete fields as '1'. Any ideas on how to get a single efficient query to act like the 2 above queries?

Sounds like a job for case ...

update messages
   set from_del = case when from = 2 then 1 else from_del end
     , to_del = case when to = 2 then 1 else to_del end
 where company_id = '1'

You're updating columns that don't need to be this way, but you're only performing one update not multiple as you would with multiple queries.

I dislike the use of from and to as column names... It just asking for confusion...

If you're performing an update that requires two different WHERE clauses, then unfortunately you will have to perform two queries. If you are worried about performance, you could always batch them in a single TRANSACTION .

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