具有多个值的MySQL Update查询

时间:2013-11-01 12:59:40

标签: mysql sql

我在数据库中有一个表,其中包含以下记录:

match_id | guess | result
   125   |   1   |   0
   130   |   5   |   0
   233   |   11  |   0
   125   |   2   |   0

我的用户为每个匹配选择一个猜测,我有一个函数可以根据匹配结果计算猜测的结果: 如果猜测正确,结果将是(1) 如果错了,结果将是(2) 如果匹配没有完成,结果将是(0默认) 我有十一种猜测的可能性(同时有多种可能是正确的) 例如:如果我匹配whit id = 125并且除了8,11之外我猜错了 所以我应该更新所有匹配ID匹配的结果字段,他们的猜测是8或11(我将为此结果字段给1) 我想给(2)同一场比赛的其他猜测

我将此查询用于以下所有11种可能性:

UPDATE `tahminler` SET result=1 WHERE match_id='1640482' AND tahmin='8'
UPDATE `tahminler` SET result=1 WHERE match_id='1640482' AND tahmin='11'
UPDATE `tahminler` SET result=0 WHERE match_id='1640482' AND tahmin='1'
UPDATE `tahminler` SET result=0 WHERE match_id='1640482' AND tahmin='2'
UPDATE `tahminler` SET result=0 WHERE match_id='1640482' AND tahmin='3'
UPDATE `tahminler` SET result=0 WHERE match_id='1640482' AND tahmin='4'
UPDATE `tahminler` SET result=0 WHERE match_id='1640482' AND tahmin='5'
UPDATE `tahminler` SET result=0 WHERE match_id='1640482' AND tahmin='6'
UPDATE `tahminler` SET result=0 WHERE match_id='1640482' AND tahmin='7'
UPDATE `tahminler` SET result=0 WHERE match_id='1640482' AND tahmin='9'
UPDATE `tahminler` SET result=0 WHERE match_id='1640482' AND tahmin='10'

我想知道我是否可以在一个查询中完成这项工作?或者不是?

3 个答案:

答案 0 :(得分:5)

使用这两个查询:

UPDATE `tahminler` 
        SET result=0 
        WHERE match_id='1640482' 
              AND tahmin IN ('1','2','3','4','5','6','7','9','10')

然后使用它:

UPDATE `tahminler` 
        SET result=1 
        WHERE match_id='1640482' 
              AND tahmin IN ('8','11')

答案 1 :(得分:4)

你可以这样做,但也会很难看。使用CASE()运算符,例如:

UPDATE tahminler
SET
  result=CASE
    WHEN tahmin IN ('1','2','3','4','5','6','7','8','9','10') THEN 0
    WHEN tahmin IN ('8', 11) THEN 1
  END
WHERE
  match_id='1640482'

答案 2 :(得分:1)

UPDATE `tahminler` SET `result` = CASE WHEN tahmin IN(8,11) THEN 1
                                   WHEN tahmin IN(2,3,4,5,6,7,9,10) THEN 0
                              END
 WHERE match_id = 1640482;