简体   繁体   中英

CASE statement updates all my values to NULL when there is no matches?

I'm having an issue using the CASE statement in MySql. I added some code below as an example of what I'm trying to do. I thought that if there are no matches in the WHEN statement that no changes will occur, but that doesn't seem to happen.

I don't have a record that has a value 66 for contact_id in the my_contacts table, so I figured nothing will happen, but instead all the values in the zip_code column change to null. Why is this?

UPDATE my_contacts
SET zip_code =
CASE
 WHEN contact_id = 66 THEN '33333'
END;

How Do i only update a few records using case? For instance, I want to update only records that match contact_id = 1 and contact_id =2. It does update those two records, but also changes an existing zip code from '90004' to NULL, Why is that?

UPDATE my_contacts 
SET zip_code = 
CASE 
WHEN contact_id = 1 THEN '94301' 
WHEN contact_id = 2 THEN '08540' 
END; 

Query OK, 3 rows affected (0.01 sec) Rows matched: 5 Changed: 3 Warnings: 0

You're using CASE incorrectly. Use a WHERE clause for a conditional update:

UPDATE my_contacts SET zip_code = '33333' WHERE contact_id = 66;

A CASE expression merely decides what value to return - not which rows are affected. From the documentation :

If there [is] no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part.

So what you're doing is equivalent to this:

UPDATE my_contacts
SET zip_code = CASE WHEN contact_id = 66 THEN '33333' ELSE NULL END
;

In response to your update, you would need to do the following:

UPDATE my_contacts 
SET zip_code =
    CASE 
        WHEN contact_id = 1 THEN '94301' 
        WHEN contact_id = 2 THEN '08540' 
    END
WHERE contact_id IN (1, 2)
;

But it only makes sense to do this for a few records. See this post for more scaleable solutions: MySQL bulk INSERT or UPDATE

UPDATE my_contacts 
 SET zip_code = 
    CASE  
        WHEN contact_id =  1  THEN  '94301'  
        WHEN contact_id =  2  THEN  '08540' 
    ELSE zip_code
    END 
;

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