繁体   English   中英

在mysql中获取连续记录

[英]get consecutive records in 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获得连续获胜(win = 1),对于user_id = 2(记录id = 5),它应该返回4(记录id 10,11,12,13),它应该返回1。

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

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

内部查询计算每个条纹。 外部查询获得每个用户的最大值。 查询未经测试(但基于有效的查询)

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

不确定你是否设法让其他查询工作,但这是我的尝试, 绝对正在工作 - 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);}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM