如何在查询中用0替换NULL?

时间:2016-06-16 12:58:40

标签: php mysql sql

我有这个问题:

$db->prepare("UPDATE users 
               SET reputation = reputation +
                               (CASE WHEN id = ? THEN 2
                                     WHEN id = ? AND NOT ? THEN 15 END)
              WHERE id IN (?, ?); ")
->execute(array($author_ques_id, $author_ans_id, $isOwnAnswer,
                $author_ans_id, $author_ques_id));

请关注这一行:

WHEN id = ? AND NOT ? THEN 15 END)

NOT ? false (换言之$isOwnAnswer = true时,此类用户的reputatuin值将为NULL。因为reputation = reputation + NULL会评估reputation = NULL

那我该如何预防?我希望当条件 false 时,reputation不会改变。

2 个答案:

答案 0 :(得分:3)

无需使用其他CASE/COALESCE/IFNULL或其他任何内容,只需使用CASE EXPRESSION ELSE,如果不满足所有条件,将使用ELSE

UPDATE users 
           SET reputation = reputation +
                            CASE WHEN id = ? THEN 2
                                 WHEN id = ? AND NOT ? THEN 15
                                 ELSE 0
                            END
          WHERE id IN (?, ?);

答案 1 :(得分:2)

使用COALESCE

UPDATE users 
SET reputation = reputation +
                 COALESCE((CASE 
                             WHEN id = ? THEN 2
                             WHEN id = ? AND NOT ? THEN 15 
                           END), 0)