数据库
首页 > 数据库> > mysql – 使用CASE WHEN查询

mysql – 使用CASE WHEN查询

作者:互联网

我试图写这样的查询,我收到一个错误.这是我第一次使用案例,所以我认为问题就在于此.

UPDATE my_table 
       CASE
              WHEN downloads IS NULL THEN 
              SET    downloads = 1 
              ELSE 
              SET    downloads + 1 
       END
WHERE  attachment_id = 8990 
AND    parent_post_id = 9221 
OR     attachment_id = 9211 
AND    parent_post_id = 383

解决方法:

你可以重写如下

UPDATE my_table 
SET downloads = CASE WHEN downloads IS NULL THEN  1 
                ELSE downloads + 1 END
WHERE attachment_id = 8990 
AND (parent_post_id = 9221 
OR attachment_id = 9211 )
AND parent_post_id = 383

你还需要在()中对你的或条件进行分组,以便将9211与parent_post_id和attachment_id与或者操作相匹配,同样在你的查询中你有一些令人困惑的条件,如何parent_post_id和attachment_id可以同时等于2个值可能是你正在找

WHERE (attachment_id = 8990  AND parent_post_id = 9221 ) 
OR (attachment_id = 9211  AND parent_post_id = 383)

标签:case-when,mysql,sql-update
来源: https://codeday.me/bug/20190824/1713391.html