Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL通过ID查找下一行值_Mysql_Sql - Fatal编程技术网

MySQL通过ID查找下一行值

MySQL通过ID查找下一行值,mysql,sql,Mysql,Sql,我希望格式为: id month status 1 1997-11-01 A 1 2015-08-01 B 2 2010-01-01 A 2 2010-02-01 B 2 2012-10-01 C MySQL对我来说是新手,我很难理解变量。我更喜欢使用带有分区的简单LEAD(),但不幸的是,我不能 这是我的尝试,但不起作用: id month lead_month status 1 1997-11-01

我希望格式为:

id    month     status
1   1997-11-01    A
1   2015-08-01    B
2   2010-01-01    A
2   2010-02-01    B
2   2012-10-01    C
MySQL对我来说是新手,我很难理解变量。我更喜欢使用带有
分区的简单
LEAD()
,但不幸的是,我不能

这是我的尝试,但不起作用:

id    month      lead_month    status
 1  1997-11-01   2015-08-01      A
 1  2015-08-01     NOW()         B
 2  2010-01-01   2010-02-01      A
 2  2010-02-01   2012-10-01      B
 2  2012-10-01     NOW()         C
输出如下所示,它也不会检查行与行之间的id是否相同:

SET @lead = '1995-01-01'; --abitrary floor

select id, month, status, @lead, @lead:=month from table

不要在MySQL中乱搞变量。这种逻辑最好存在于应用程序使用的任何语言中。但是,这可以在SQL中完成

我的第一反应就是将数据保存在一个额外的列中。不要担心db的大小——宇宙中没有足够的月份成为问题

您的ID也有问题:这些应该几乎总是主键,即。E独一无二

如果你坚持你的计划,你可以加入。假设连续唯一ID:


选择a.id、a.month、b.month作为lead_month,从表中选择status作为LEFT JOIN表作为b,其中a.id-1=b.id;

您可以使用相关子查询:

id    month      lead_month  status
 1  1997-11-01   1995-01-01    A
 1  2015-08-01   1997-11-01    B
 2  2010-01-01   2015-08-01    A
 2  2010-02-01   2010-01-01    B
 2  2012-10-01   2010-02-01    C
如果要替换每个id最后一个月的值,则可以使用
coalesce()

select t.*,
       (select t2.month
        from t t2
        where t.id = t2.id
        order by t2.month desc
        limit 1
       ) as next_month
from t;
select t.*,
       coalesce((select t2.month
                 from t t2
                 where t.id = t2.id
                 order by t2.month desc
                 limit 1
                ), now()) as next_month
from t;