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 

user_id = 1の場合はmysql.likeの各ユーザーに対して連続したwins(win = 1)を取得したいのですが、user_id = 2(record id = 5)の場合は4(record id 10,11,12,13)を返す必要があります。 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 に答える