简体   繁体   English

当没有匹配项时,CASE语句会将我的所有值更新为NULL?

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

I'm having an issue using the CASE statement in MySql. 我在MySql中使用CASE语句时遇到问题。 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. 我以为,如果WHEN语句中没有匹配项,则不会发生任何更改,但这似乎没有发生。

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. 我没有my_contacts表中的contact_id值为66的记录,因此我认为什么也不会发生,但是zip_code列中的所有值都更改为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. 例如,我只想更新与contact_id = 1和contact_id = 2匹配的记录。 It does update those two records, but also changes an existing zip code from '90004' to NULL, Why is that? 它会更新这两个记录,但还会将现有的邮政编码从“ 90004”更改为NULL,这是为什么呢?

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 查询正常,受影响的3行(0.01秒)匹配的行:5已更改:3警告:0

You're using CASE incorrectly. 您使用的CASE错误。 Use a WHERE clause for a conditional update: 使用WHERE子句进行条件更新:

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. CASE表达式仅确定要返回的值-不会影响哪些行。 From the documentation : 文档中

If there [is] no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part. 如果没有匹配的结果值,则返回ELSE之后的结果;如果没有ELSE部分,则返回NULL

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 有关更多可扩展的解决方案,请参见此帖子: MySQL批量INSERT或UPDATE

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM