If you work with a lot of data, this method may not be feasible (I am inexperienced with large databases), but maybe this can help.
The idea is to create subqueries to extract adjacent rows:
mysql> select id, load_status, (select load_status from test as t2 where t2.id < t1.id order by t2.id desc limit 1) as prev_load_status, (select load_status from test as t3 where t3.id > t1.id order by t3.id asc limit 1) as next_load_status from test as t1; +----+-------------+------------------+------------------+ | id | load_status | prev_load_status | next_load_status | +----+-------------+------------------+------------------+ | 1 | success | NULL | success | | 2 | success | success | success | | 3 | success | success | fail | | 4 | fail | success | success | | 5 | success | fail | NULL | +----+-------------+------------------+------------------+ 5 rows in set (0.00 sec)
I initially threw a HAVING there to limit the results to clusters:
mysql> select id, load_status, (select load_status from test as t2 where t2.id < t1.id order by t2.id desc limit 1) as prev_load_status, (select load_status from test as t3 where t3.id > t1.id order by t3.id asc limit 1) as next_load_status from test as t1 having load_status = prev_load_status or load_status = next_load_status; +----+-------------+------------------+------------------+ | id | load_status | prev_load_status | next_load_status | +----+-------------+------------------+------------------+ | 1 | success | NULL | success | | 2 | success | success | success | | 3 | success | success | fail | +----+-------------+------------------+------------------+ 3 rows in set (0.00 sec)
But it turns out that you can put subqueries directly in the WHERE :
mysql> select id, load_status from test as t1 where load_status = (select load_status from test as t2 where t2.id < t1.id order by t2.id desc limit 1) or load_status = (select load_status from test as t3 where t3.id > t1.id order by t3.id asc limit 1); +----+-------------+ | id | load_status | +----+-------------+ | 1 | success | | 2 | success | | 3 | success | +----+-------------+ 3 rows in set (0.00 sec)
source share