9

为什么我不能像这样使用 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

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

编辑:

如果我跑

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
4

2 回答 2

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
于 2014-02-03T17:59:21.650 回答
2

这就是我将如何重写您的查询:

UPDATE
  my_users
SET 
  position2 = position2 - 1
WHERE
  position2 >= 16
  AND position2 <= 18
  AND user_id >= 170 
  AND user_id <= 1000
于 2013-04-10T19:41:19.640 回答