Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Update with same table subquery

Tags:

sql

mysql

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?

like image 574
Michael Avatar asked Apr 21 '26 06:04

Michael


1 Answers

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 
like image 133
valex Avatar answered Apr 22 '26 19:04

valex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!