使用下一个最接近日期列的结果更新日期列

时间:2017-10-13 16:23:41

标签: mysql sql-update

我有一个MySQL表,如下所示:

+-------------+---------+------+-----+---------+-------+
| Field       | Type    | Null | Key | Default | Extra |
+-------------+---------+------+-----+---------+-------+
| person_id   | int(11) | NO   | MUL | NULL    |       |
| location_id | int(11) | NO   | MUL | NULL    |       |
| date_signed | date    | NO   |     | NULL    |       |
| date_ended  | date    | YES  |     | NULL    |       |
+-------------+---------+------+-----+---------+-------+

所有记录都是这样的:

+-----------+-------------+-------------+------------+
| person_id | location_id | date_signed | date_ended |
+-----------+-------------+-------------+------------+
|         1 |          49 | 2007-09-29  | NULL       |
|         1 |          41 | 2010-10-09  | NULL       |
|         2 |          45 | 2007-09-29  | NULL       |
|         2 |          58 | 2007-12-16  | NULL       |
|         3 |          49 | 2007-09-29  | NULL       |
|         4 |          45 | 2007-09-29  | NULL       |
|         4 |          35 | 2013-10-04  | NULL       |
|         5 |          45 | 2007-09-29  | NULL       |
|         5 |          37 | 2009-01-09  | NULL       |
|         5 |          32 | 2009-10-08  | NULL       |
+-----------+-------------+-------------+------------+

我正在尝试将每个人的date_ended更新为比该人的下一个时间顺序行中的date_signed少一天:

+-----------+-------------+-------------+------------+
| person_id | location_id | date_signed | date_ended |
+-----------+-------------+-------------+------------+
|         1 |          49 | 2007-09-29  | 2010-10-08 |
|         1 |          41 | 2010-10-09  | NULL       |
|         2 |          45 | 2007-09-29  | 2007-12-15 |
|         2 |          58 | 2007-12-16  | NULL       |
.
.
.

但我无法弄清楚如何选择下一个按时间顺序排列的记录。我尝试了类似问题的一些建议:

UPDATE a column based on the value of another column in the same table

Mysql - update table column from another column based on order

ROW_NUMBER() in MySQL

但我无法让他们工作。有没有办法在MySQL中做到这一点?

SQL小提琴:http://sqlfiddle.com/#!9/8b5219/1

0 个答案:

没有答案