UPDATE查询中的MySQL IF语句

时间:2012-07-27 23:56:21

标签: mysql if-statement

为什么我不能像这样使用IF

UPDATE my_users
    IF(position2 = 18, "SET position = 17", ''),
    IF(position2 = 17, "SET position = 16", ''),
    IF(position2 = 16, "SET position = 15", ''),
        WHERE user_id => 170 AND user_id <= 1000

唯一有效的方法是

UPDATE my_users
    SET position2 = IF(position2 = 18, 17, 
                      IF(position2 = 17, 16, 
                        IF(position2 = 16, 15, ''
                      )
                        )
                          )
        WHERE user_id => 170 AND user_id <= 1000

有没有办法以任何其他方式制作相同的东西,因为我对该字段位置2有超过40个条件并且它很容易以这种方式迷失?

修改

如果我跑

UPDATE my_users
    SET position2 = CASE position2  WHEN 18 THEN 17
                    WHEN 17 THEN 16
                    WHEN 16 THEN 15
                    END
            WHERE user_id => 170 AND user_id <= 1000

position2不在CASE语句中时,它将其设置为空,我怎样才能保留除CASE语句中的任何值以外的任何值

编辑2: 我猜解决方案是:

   UPDATE my_users
        SET position2 = CASE position2  WHEN 18 THEN 17
                        WHEN 17 THEN 16
                        WHEN 16 THEN 15
                            ELSE position2
                        END
                WHERE user_id => 170 AND user_id <= 1000

编辑3: 如果我的请求不是一次性的事情,那么更快的请求就像建议的Vatev

   UPDATE my_users
        SET position2 = CASE position2  WHEN 18 THEN 17
                        WHEN 17 THEN 16
                        WHEN 16 THEN 15
                        END
                WHERE user_id => 170 AND user_id <= 1000
                AND position2 >= 16 and <= 18

2 个答案:

答案 0 :(得分:4)

您也可以这样做:

                UPDATE my_users
                     SET position2 = CASE WHEN position2 =18 THEN 17
                        WHEN position2 =17 THEN 16
                        WHEN position2 =16 THEN 15 ELSE position2 
                        END
                WHERE user_id between 170 AND  1000
                AND position2 between 16 and  18

答案 1 :(得分:2)

这就是我重写查询的方式:

UPDATE
  my_users
SET 
  position2 = position2 - 1
WHERE
  position2 >= 16
  AND position2 <= 18
  AND user_id >= 170 
  AND user_id <= 1000