在更新语句中使用IF

时间:2013-12-26 08:50:37

标签: mysql sql

我正在尝试更新特定用户的分数,前提是他添加的文章数量为>=10

如何添加检查其artcAdded是否为>=10的部分?

在伪代码中,这将是;

update tableScores, set score = 'Good' where userId = 1 (if artcAdded for userId = 1 is >= 10) 
// Calcualate and update the score only if his artcAdded is >= 10

我现在这样做update tableScores set score = 'Good' where userId = 1 and artcAdded >=10;这有效,但这是正确的方法吗?我应该使用IF条款吗?

未处理的表格

"userId"    "artcAdded" "artcApproved"  "artcRejected"  "score"
"1"         "10"        "7"             "3"             NULL
"2"         "5"         "4"             "1"             NULL
"3"         "3"         "1"             "2"             NULL

处理后

"userId"    "artcAdded" "artcApproved"  "artcRejected"  "score"
"1"         "10"        "7"             "3"             Good
"2"         "5"         "4"             "1"             NULL
"3"         "3"         "1"             "2"             NULL

2 个答案:

答案 0 :(得分:0)

您要做的是使用简单的and语句

update tableScores, set score = 'Good' where userId = 1 and artcAdded >= 10

答案 1 :(得分:0)

update tableScores, set score = 'Good' where userId = 1 
AND artcAdded >= 10

添加AND子句是正确的方法。如果要根据特定条件更新具有不同值的列,IF CLAUSE会很有用。

例如如果artcAdded> = 10则将分数更新为“Good”,否则将其更新为“Bad”