0
id value
---------
1 a
2 b
3 c
4 a
5 t
6 y
7 a
我想選擇的所有行值是「A」和行前選擇當前和以前的行WHERE條件
id value
---------
1 a
3 c
4 a
6 y
7 a
我看着
,但我想一個查詢中的所有這樣的行。
請幫我開始
謝謝
id value
---------
1 a
2 b
3 c
4 a
5 t
6 y
7 a
我想選擇的所有行值是「A」和行前選擇當前和以前的行WHERE條件
id value
---------
1 a
3 c
4 a
6 y
7 a
我看着
,但我想一個查詢中的所有這樣的行。
請幫我開始
謝謝
我認爲最簡單的方法可能是使用變量:
select t.*
from (select t.*,
(rn := if(value = 'a', 1, @rn + 1) as rn
from table t cross join
(select @rn := 0) params
order by id desc
) t
where rn in (1, 2)
order by id;
另一種方法是使用相關子查詢來獲取先前的值,然後在where
子句中使用此:
select t.*
from (select t.*,
(select t2.value
from table t2
where t2.id < t.id
order by t2.id desc
limit 1
) as prev_value
from table t
) t
where value = 'a' or prev_value = 'a';
使用id
索引時,這可能比使用變量的方法更快。