2012-09-12 54 views
5

我有表結構如下得到連續記錄在MySQL

ID   user_id   win 
1    1    1 
2    1    1 
3    1    0 
4    1    1 
5    2    1 
6    2    0 
7    2    0 
8    2    1 
9    1    0 
10    1    1 
11    1    1 
12    1    1 
13    1    1 
14    3    1 

我希望得到連續贏得mysql.like爲USER_ID = 1(贏= 1)爲每個用戶,它應該返回4(記錄ID爲10,11,12,13),對於user_id = 2(記錄ID = 5),它應該返回1.

我可以在php中記錄每個用戶的記錄後做到這一點,但我不知道如何可以使用查詢來做到這一點。

另外什麼會更好的性能方面,使用PHP或MySQL。任何幫助將不勝感激。謝謝!

+0

爲什麼不1, 2,4,9? – 2012-09-12 21:10:57

+0

不,因爲1,2,4,9不是連續的。 user_id = 1失敗record_id = 3 –

+2

井1,2連勝,你想要最長的連勝嗎? – 2012-09-12 21:14:57

回答

1

不知道,如果你已經成功地得到其他查詢工作,但這裏是我嘗試的,我確​​定工作 - Sqlfiddle來證明這一點。

set @x=null; 
set @y=0; 

select sub.user_id as user_id,max(sub.streak) as streak 
from 
(
select 
case when @x is null then @x:=user_id end, 
case 
when win=1 and @x=user_id then @y:[email protected]+1 
when win=0 and @x=user_id then @y:=0 
when win=1 and @x<>user_id then @y:=1 
when win=0 and @x<>user_id then @y:=0 
end as streak, 
@x:=user_id as user_id 
from your_table 
) as sub 
group by sub.user_id 

如何得到它的一個PHP頁面和測試上工作,看看你得到正確的結果在下面,我也優化了查詢了一下:

mysql_query("set @y=0"); 
$query=mysql_query("select sub.user_id as user_id,max(sub.streak) as streak 
from 
(
select 
case 
when win=1 and @x=user_id then @y:[email protected]+1 
when win=0 and @x=user_id then @y:=0 
when win=1 and @x<>user_id then @y:=1 
when win=0 and @x<>user_id then @y:=0 
end as streak, 
@x:=user_id as user_id 
from your_table 
) as sub 
group by sub.user_id"); 
while($row=mysql_fetch_assoc($query)){ 
print_r($row);} 
+0

謝謝!!它的工作。感謝很多:) –

+0

嗨,執行此查詢使用php中的mysql_query函數不返回任何東西,而這對phpmyadmin工作正常。任何建議。謝謝 –

+0

@PriteshGupta嗨,我編輯了我的帖子,包括我如何在我做的一個php頁面上工作。 – mrmryb

4

內部查詢計數每個連勝。外部查詢獲取每個用戶的最大值。查詢是未經檢驗的(但基於一個工程)

set @user_id = null; 
set @streak = 1; 

select user_id, max(streak) from (
    SELECT user_id, streak, 
    case when @user_id is null OR @user_id != user_id then @streak := 1 else @streak := @streak + 1 end as streak_formula, 
    @user_id := user_id, 
    @streak as streak 
    FROM my_table 
) foo 
group by user_id 
+0

我正在測試它。會很快讓你知道。 –

+0

我無法爲mysql運行它。請你好好解釋一下,這樣我可以糾正我做錯的事情。我用我的表名替換了my_table。另一件事情需要改變? –

+0

你會得到什麼錯誤? my_table是否包含名爲user_id的列? –