在更新语句中添加If

时间:2013-10-01 07:31:22

标签: mysql sql

我正在尝试在update语句中添加IF子句。认为这很容易,但似乎不是。

就是这样。它在存储过程中。

FETCH cur1 INTO procId, procType, procVals, procLen, procUpdated, procPrivate, procRegional;

    IF done THEN
      LEAVE the_loop;
    END IF;

    UPDATE scores t1
        JOIN scores t2
        ON FIND_IN_SET(t1.id, t2.vals)
        SET t1.private = t1.private+1,
        IF procType = 3 THEN // Problem lies here
             t1.regional = t1.regional+1;
            ELSE IF procType = 4 THEN
             t1.otherCol = t1.otherCol+1;
          END IF;
    WHERE t2.id = procId;

我坚持使用IF。除了第一个SET之外,我还需要使用Update IF另一列。

3 个答案:

答案 0 :(得分:1)

UPDATE scores t1
JOIN scores t2
ON FIND_IN_SET(t1.id, t2.vals)
SET t1.private = t1.private+1,
    CASE  procType 
    WHEN 3  THEN t1.regional = t1.regional+1
    WHEN 4  THEN t1.otherCol = t1.otherCol+1
    END as Col
WHERE t2.id = procId

答案 1 :(得分:1)

UPDATE scores t1
JOIN scores t2
ON FIND_IN_SET(t1.id, t2.vals)

SET t1.private = t1.private+1 
t1.regional = IF (procType = 3, t1.regional + 1, t1.regional)
t1.otherCol = IF (procType = 4, t1.otherCol + 1, t1.otherCol)
WHERE t2.id = procId

答案 2 :(得分:1)

将它们分成两个单独的更新语句会更简单,因为您要更新到不同的字段

IF procType = 3 THEN
    UPDATE scores t1
        JOIN scores t2
        ON FIND_IN_SET(t1.id, t2.vals)
    SET t1.private = t1.private+1,
     t1.regional = t1.regional+1;
    WHERE t2.id = procId;

ELSE IF procType = 4 THEN

    UPDATE scores t1
        JOIN scores t2
        ON FIND_IN_SET(t1.id, t2.vals)
    SET t1.private = t1.private+1,
        t1.otherCol = t1.otherCol+1;
    WHERE t2.id = procId;