3

I have a table (EMP_ID, START_DATE, END_DATE) that contains a series of date ranges. What I want to do is ensure that they are all contiguous, so the END_DATE should be one less than the next START_DATE for any given EMP_ID.
I have the following query that lets me identify the records that are not contiguous:

  SELECT H.EMP_ID, 
         H.START_DATE, 
         H.END_DATE,
         DATE(
                 (   SELECT MIN(START_DATE) 
                       FROM TSRHierarchy I
                      WHERE I.START_DATE > H.START_DATE 
                        AND I.EMP_ID = H.EMP_ID
                  )
             ) AS NEXT_DATE 
    FROM TSRHierarchy H
  HAVING END_DATE <> DATE_ADD(NEXT_DATE, INTERVAL -1 DAY)
ORDER BY H.EMP_ID, H.START_DATE;

What I can't do is figure out how to turn this into an UPDATE statement? The MySQL documentation states 'Currently, you cannot update a table and select from the same table in a subquery.' which may be part of my problem.
Any suggestions for a work-around?

1 Answer 1

1

Try this UPDATE query using JOIN

UPDATE TSRHierarchy t
         JOIN
           ( SELECT H.EMP_ID, 
                    H.START_DATE, 
                    H.END_DATE,
                    DATE((SELECT MIN(START_DATE) 
                                 FROM TSRHierarchy I
                                      WHERE I.START_DATE > H.START_DATE 
                                      AND I.EMP_ID = H.EMP_ID
                        )) AS NEXT_DATE 
             FROM TSRHierarchy H
             HAVING END_DATE <> DATE_ADD(NEXT_DATE, INTERVAL -1 DAY)
           ) AS t2
         ON t.EMP_ID = t2.EMP_ID
SET t.END_DATE = t2.NEXT_DATE 
Sign up to request clarification or add additional context in comments.

Comments

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.