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

UPDATE multiple fields under same condition (IF or 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?或者有其他更好的选择吗?

提前致谢。

不幸的是,您需要为您尝试设置的每个字段重复您的案例。所以你会这样做:

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

在我看来,您的 table 结构有问题,或者您应该考虑使用多个查询来解决您的问题。

编辑:由于我是代码可读性的忠实拥护者,如果性能不是问题而且永远不会是,我将分两步进行:

  1. 遍历所有符合条件的记录(在MySQL或您选择的后端语言中)
  2. 在更新之前编辑循环内的记录,如果你这样做正确,你不需要重复你的条件两次。

过度优化是不好的,在大多数情况下,代码的可读性更重要。