获取mysql中具有多行的列的下一个值/行

时间:2016-06-03 06:52:17

标签: mysql

我的桌子就像这样::

+-------+-----------------+---+
 id     |  created             |
+-------+-----------------+---+
| 2sdv  | 2016-05-18 14:08:14 |
| 2sdv  | 2016-05-18 14:25:22 |
| 2sdv  | 2016-05-18 14:26:01 |
| 2sdv  | 2016-05-19 07:19:13 |
+-------+---------------------+

假设在这些日期创建了这个id ='2sdv' 我希望输出就像这样

+-------+-----------------+---+------+-----------------+
 id     |  created            | new_date
+-------+-----------------+---+------+-----------------+
| 2sdv  | 2016-05-18 14:08:14 | 2016-05-18 14:25:22    |
| 2sdv  | 2016-05-18 14:25:22 | 2016-05-18 14:26:01    |
| 2sdv  | 2016-05-18 14:26:01 | 2016-05-19 07:19:13    |
| 2sdv  | 2016-05-19 07:19:13 |
+-------+---------------------+------+-----------------+

Oracle我们可以使用lead()函数,但我希望我的查询位于MySQL。 如何在多行fetch中的新列中获取创建日期列的下一个值。

1 个答案:

答案 0 :(得分:1)

根据我上面的评论......

SELECT x.*
     , MIN(y.created) new_date -- the minimum y date...
  FROM my_table x 
  LEFT 
  JOIN my_table y 
    ON y.id = x.id 
   AND y.created > x.created -- ... greater than the corresponding x date
 GROUP 
    BY x.id
     , x.created;