2016-04-20 98 views
0

我有这个表:如何在更新之前检查记录的值?

// QandA 
+----+-----------+-----------------+-------------+------+------+ 
| id | post | accepted-answer | question_id | let | type | 
+----+-----------+-----------------+-------------+------+------+ 
| 1 | question1 | null   | 1   | 200 | 0 | 
| 2 | answer1 | null   | 1   | null | 1 | 
| 3 | answer2 | 1    | 1   | null | 1 | 
| 4 | answer3 | null   | 1   | null | 1 | 
+----+-----------+-----------------+-------------+------+------+ 
//              ^0 = question | 1 = answer 

我也有这个疑问:

// this query changes accepted answer 
UPDATE QandA 
SET accepted_answer = IF(id <> :id, NULL, 1) 
WHERE question_id = :question_id; 

现在我想要在更新前检查let领域。这样的事情:

if (`let` is null) then {update here} 
else {don't update} 
where `question_id` = :question_id and `type` = 0 

我怎么能在MySQL中做到这一点?

+2

你可以在哪里添加''和'let'为null''吗? – Kateract

+0

@Kateract emm,似乎是正确的,我认为这是更难..无论如何谢谢你,我会尝试它。 – stack

回答

1

你可以使用case语句,下面的语句将更新QandA表。

这将设置accepted_answer为1时设为空并且类型为0

试试看吧,我知道它在MS SQL,只是不能访问我的SQL框的时刻。

UPDATE QandA SET accepted_answer = 
CASE 
    WHEN let = IS NULL THEN 1 
END 
WHERE type= 0; 
+0

谢谢..投票。实际上,不是只有一行'type = 0'。所以我认为你必须改善查询中的where子句。 – stack

+0

我相信你可以添加额外检查你想'question_id' =:question_id在哪里,如果是这样,只需检查。 – justinf

相关问题