在相同条件下更新多个字段(IF或CASE)

时间:2015-03-26 18:45:06

标签: mysql if-statement sql-update case

需要一些帮助。这里有一些关于这个主题的问题和答案,但没有找到符合我需要的问题。

我有这两个问题:

UPDATE leilaov
   SET seconds = CASE
      WHEN (mesini = MONTH(NOW()) AND diaini = DAYOFMONTH(NOW()) AND horaini = HOUR(NOW()) AND minutoini <= MINUTE(NOW())) 
        OR (mesini = MONTH(NOW()) AND diaini < DAYOFMONTH(NOW())) 
        OR (mesini = MONTH(NOW()) AND diaini = DAYOFMONTH(NOW()) AND horaini < HOUR(NOW()))
        OR (mesini < MONTH(NOW())) THEN seconds-1
   END
WHERE numero12345 = 1


UPDATE leilaov
   SET seconds = IF((mesini = MONTH(NOW()) AND diaini = DAYOFMONTH(NOW()) AND horaini = HOUR(NOW()) AND minutoini <= MINUTE(NOW())) 
                OR (mesini = MONTH(NOW()) AND diaini < DAYOFMONTH(NOW())) 
                OR (mesini = MONTH(NOW()) AND diaini = DAYOFMONTH(NOW()) AND horaini < HOUR(NOW()))
                OR (mesini < MONTH(NOW())), seconds-1, seconds)
WHERE numero12345 = 1

两者都工作正常,执行时间没有显着差异。 问题是我需要更新几个字段而不仅仅是一个字段。

更新多个字段的语法是什么?我是否必须重复每个领域的条件?

我应该使用CASE还是IF?或者还有其他更好的选择吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

不幸的是,您需要针对您尝试设置的每个字段重复您的情况。所以你要这样做:

UPDATE leilaov
   SET seconds = CASE
      WHEN (mesini = MONTH(NOW()) AND diaini = DAYOFMONTH(NOW()) AND horaini = HOUR(NOW()) AND minutoini <= MINUTE(NOW())) 
        OR (mesini = MONTH(NOW()) AND diaini < DAYOFMONTH(NOW())) 
        OR (mesini = MONTH(NOW()) AND diaini = DAYOFMONTH(NOW()) AND horaini < HOUR(NOW()))
        OR (mesini < MONTH(NOW())) THEN seconds-1
   END,
, second_field = CASE
          WHEN (mesini = MONTH(NOW()) AND diaini = DAYOFMONTH(NOW()) AND horaini = HOUR(NOW()) AND minutoini <= MINUTE(NOW())) 
            OR (mesini = MONTH(NOW()) AND diaini < DAYOFMONTH(NOW())) 
            OR (mesini = MONTH(NOW()) AND diaini = DAYOFMONTH(NOW()) AND horaini < HOUR(NOW()))
            OR (mesini < MONTH(NOW())) THEN seconds-1
       END

WHERE numero12345 = 1

我认为您的表格结构有问题,或者您应该考虑使用多个查询来解决您的问题。

编辑:由于我是代码可读性的忠实粉丝,如果性能不是问题而且永远不会,我会分两步完成:

  1. 遍历所有符合条件的记录(使用MySQL或您选择的后端语言)
  2. 在更新之前编辑循环内的记录,如果你这样做,你将不需要重复你的条件两次。
  3. 过度优化很糟糕,在大多数情况下,代码可读性更重要。