7

I'm not even sure if this is possible but I'm trying to do different UPDATE if a certain condition is met.

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)]

What I have right now is this but this only works if a role exists for the user and it's end_date is 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

I was thinking of doing something like this:

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
  • @APC, I was doing same thing =) Commented Dec 11, 2009 at 9:48

1 Answer 1

14

Since the only difference is whether you are setting ur.end_Date to either the current Date or setting it to it's existing date could you not just use the following:

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
Sign up to request clarification or add additional context in comments.

1 Comment

That makes much more sense indeed... it works perfectly. Thanks Martin!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.