在mysql中获取连续记录

时间:2012-09-12 21:06:15

标签: php 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 

对于user_id = 1,我想为mysql.like中的每个用户获得连续的胜利(win = 1),对于user_id = 2,它应该返回4(记录id 10,11,12,13)(记录id = 5),它应该返回1.

我可以在为每个用户重新审阅记录之后在php中执行此操作,但我不知道如何使用查询到mysql来执行此操作。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);}