查找连续的最后一行

查找连续的最后一行

本文介绍了查找连续的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要查询方面的帮助.

I need some help with a query.

我有一个简单的表:

CREATE TABLE `consecutiv` (
  `id` int(11) NOT NULL auto_increment,
  `readVal` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;


insert  into `consecutiv`(`id`,`readVal`) values (1,2),(2,2),(3,2),(5,3),(6,3),(7,3),(8,3),(9,4),(10,5),(11,6),(12,6),(13,2),(14,2),(15,6);

看起来像这样:

id  readVal
    1   2
    2   2
    3   2
    5   3
    6   3
    7   3
    8   3
    9   4
   10   5
   11   6
   12   6
   13   2
   14   2
   15   6

我想为给定的readVal获得最后的连续行:

I want to get for a given readVal the last consecutive row:

在上面的示例中为:

id:readVal = 2时为3

id: 3 for readVal = 2

id:readVal = 3时为8

id: 8 for readVal = 3

...

我尝试了以下查询:

SELECT consecutiv.id, consecutiv.readVal, c.id, c.readVal  FROM consecutiv
JOIN consecutiv c ON consecutiv.id = c.id-1
WHERE consecutiv.readVal!=c.readVal ORDER BY consecutiv.id ASC

并且只要该序列中没有丢失的ID,它就可以工作.在上面的示例中,id缺少4,查询将不会返回预期的结果.

And it works as long as there are no missing id's in the series. In the above example id no 4 is missing and the query won't return the expected result.

谢谢!

推荐答案

SELECT a.id, a.readVal
FROM consecutiv a
WHERE a.readVal !=
   (SELECT b.readVal
    FROM consecutiv b
    WHERE b.id > a.id
    ORDER BY id ASC
    LIMIT 1)
ORDER BY a.id;

返回:

 id | readval
----+---------
  3 |       2
  8 |       3
  9 |       4
 10 |       5
 12 |       6
 14 |       2

对于也需要最后一行的情况:

for the case that the very last row is also needed:

SELECT c.id, c.readVal, c.nextReadVal
FROM
  (SELECT
   a.id, a.readVal,
     (SELECT b.readVal
      FROM consecutiv b
      WHERE b.id > a.id
      ORDER BY id ASC
      LIMIT 1) AS nextReadVal
   FROM consecutiv a) AS c
WHERE readVal != nextReadVal OR nextReadVal IS NULL
ORDER BY c.id;

返回:

 id | readval | nextreadval
----+---------+-------------
  3 |       2 |           3
  8 |       3 |           4
  9 |       4 |           5
 10 |       5 |           6
 12 |       6 |           2
 14 |       2 |           6
 15 |       6 |

这篇关于查找连续的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 12:02