Try
UPDATE Table1 t1 JOIN
(
SELECT id, @n := @n + 1 rnum
FROM Table1 CROSS JOIN (SELECT @n := 0) i
WHERE date IS NULL
ORDER BY id
) t2 ON t1.id = t2.id CROSS JOIN
(
SELECT MAX(date) date FROM Table1
) q
SET t1.date = q.date + INTERVAL t2.rnum DAY
Result:
| ID | DATE | ---------------------- | 10500 | 2013-08-18 | | 10501 | 2013-08-16 | | 10502 | 2013-08-17 | | 10503 | 2013-08-19 | | 10504 | 2013-08-20 | -- date has been assigned | 10505 | 2013-08-21 | -- date has been assigned
Here is SQLFiddle demo
Explanation: In a subquery with an alias t2 we grab all rows where date IS NULL order them by id
and assign row numbers starting from 1. Unfortunately MySql doesn't have an implementation for ROW_NUMBER()
function so we do it with a user variable @n
which is incremented while rows are selected. To initialize this variable we use a subquery with an alias i
. And use CROSS JOIN
to make it available for our subquery t2
. We then use the same technique (CROSS JOIN
) to grab a max date in the table and make it available for every row in our JOIN
. ONce we have all that we just add a line number, which represents a number of days) add it to the max date and assign to date
column in our table.