2012-09-12 55 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的列? –