title: MySQL UPDATE using IF condition
body: <p>I'm not even sure if this is possible but I'm trying to do different UPDATE if a certain condition is met.</p>
  
  <p>user [id, start_date(NOT NULL), end_date(NULL), reason(NULL),  .....]</p>
  
  <p>user_roles [id, role_id, user_id, start_date(NOT NULL), end_date(NULL)]</p>
  
  <p>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:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I was thinking of doing something like this:</p>
  
  <pre><code>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
  </code></pre>