5

我的表结构如下

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中的每个用户获得连续的胜利(win = 1)。对于user_id = 1,它应该返回4(记录id 10,11,12,13),对于user_id = 2(记录id = 5),它应该返回 1。

在为每个用户检索记录后,我可以在 php 中执行此操作,但我不知道如何使用对 mysql 的查询来执行此操作。

还有什么在性能方面会更好,使用 php 或 mysql。任何帮助将不胜感激。谢谢!!!

4

2 回答 2

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
于 2012-09-12T21:27:33.593 回答
2

不确定您是否已设法使其他查询正常工作,但这是我的尝试,绝对有效 - 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:=@y+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:=@y+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);}
于 2012-09-12T22:30:13.040 回答