使用IF条件的MySQL UPDATE

时间:2009-12-11 09:43:02

标签: mysql

我甚至不确定这是否可行,但如果满足某个条件,我会尝试进行不同的更新。

user [id,start_date(NOT NULL),end_date(NULL),reason(NULL),.....]

user_roles [id,role_id,user_id,start_date(NOT NULL),end_date(NULL)]

我现在拥有的是这个,但只有在用户存在角色并且end_date为NULL时才有效:

UPDATE user p 
JOIN user_roles ur ON p.id = ur.user_id 
SET ur.end_date = NOW()
   , p.end_date = NOW()
   , p.reason = "Retired" 
WHERE p.id = 5 
AND ur.end_date IS NULL

我在考虑做这样的事情:

IF EXISTS (SELECT id FROM user_roles 
WHERE user_id = 5 AND end_date IS NULL)
THEN 
    UPDATE user p 
    JOIN user_roles ur ON p.id = ur.user_id 
    SET ur.end_date = NOW()
        , p.end_date = NOW()
        , p.reason = "Retired" 
    WHERE p.id = 5 AND ur.end_date IS NULL 
ELSE 
    UPDATE user 
    SET end_date = NOW()
        , reason = "Retired" 
    WHERE id = 5 
END IF

1 个答案:

答案 0 :(得分:14)

由于唯一的区别在于您是将ur.end_Date设置为当前日期还是将其设置为现有日期,您不能只使用以下日期:

UPDATE user p  
JOIN user_roles ur 
ON p.id = ur.user_id  
SET 
ur.end_date = IF (ur.end_date IS NULL, NOW(), ur.end_date),
p.end_date = NOW(), 
p.reason = "Retired" 
WHERE p.id = 5