MYSQL使用INNER JOIN和if更新表

时间:2017-11-12 04:13:18

标签: mysql

我创建了一个使用INNER JOIN的SQL语句,但我还希望在gh.userGenbaStatus

时添加其他更新gh.userGenbaStatus == 2的案例
UPDATE manager.user u INNER JOIN manager.genbahistory gh
    ON u.userId = gh.userId AND gh.genbaHistoryStatus = 1
    SET u.userStatus = 5, gh.genbaHistoryStatus = 0
    WHERE u.userId = #{userId}

    if(gh.userGenbaStatus==2){
    SET gh.userGenbaStatus = 1
    }

我希望插入符合我的更新sql语句的if(){}代码。我可以有任何建议或帮助吗?

1 个答案:

答案 0 :(得分:0)

您可以将if伪代码转换为使用CASE表达式:

UPDATE manager.user u
INNER JOIN manager.genbahistory gh
    ON u.userId = gh.userId
SET
    u.userStatus = 5,
    gh.genbaHistoryStatus = 0,
    gh.userGenbaStatus = CASE WHEN gh.userGenbaStatus = 2
                              THEN 1 ELSE gh.userGenbaStatus END
WHERE
    gh.genbaHistoryStatus = 1 AND
    u.userId = #{userId};