2010-06-22 88 views
4

我需要一些幫助來查詢。找到最後一個連續的行

我有這個簡單的表:

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最後連續行:

在上面的例子將是:

id:3 for readVal = 2

ID:8 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系列中的它的工作原理。在上面的示例中,缺少4號,查詢不會返回預期的結果。

謝謝!

+1

你說你希望'ID: 3 for readVal = 2'肯定最後一個連續的是13/14? – 2010-06-22 11:08:16

回答

3
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 

的情況下的最後一行還需要:

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 | 
+0

@rudi目前這是返回2結果readval = 2。編輯哦我看到我想* *「我想爲給定的readVal獲得最後一個連續的行:」* OP表示每對中的最後一個不在表中的最後一個連續對中。在這種情況下,這看起來像是最好的答案! – 2010-06-22 11:24:39

+0

是的!這正是我所期待的。謝謝! – Bogdan 2010-06-22 11:27:20

+1

您確定在結果中不需要id爲15(val 6)的行嗎?根據你對「最後連續排」的定義,它應該被返回,或者? (我也會爲這種情況添加一個查詢) – 2010-06-22 11:42:30

相關問題