MySQL query to update records with incremented date

≯℡__Kan透↙ 提交于 2019-12-04 19:30:59

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.

Use join syntax instead:

UPDATE my_table cross join
       (SELECT max(date) as maxdate FROM my_table) const
SET my_table.date = DATE_ADD(const.maxdate, INTERVAL 1 DAY)
WHERE my_table.date IS NULL;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!