Reputation: 387
I am running following query to find the best winning streak for user.
$sql="select sub.user_id as user_id,max(sub.streak) as streak,max(sub.units) as units
from
(
select
case when @x is null then @x:=user_id end,
case
when awarded_unit>0 and @x=user_id then @y:=@y+1
when awarded_unit<0 and @x=user_id then @y:=0
when awarded_unit>0 and @x<>user_id then @y:=1
when awarded_unit<0 and @x<>user_id then @y:=0
end as streak,
case
when awarded_unit>0 and @x=user_id then @z:=@z+awarded_unit
when awarded_unit<0 and @x=user_id then @z:=0
when awarded_unit>0 and @x<>user_id then @z:=awarded_unit
when awarded_unit<0 and @x<>user_id then @z:=0
end as units,
@x:=user_id as user_id,
awarded_unit
from $select_user_events_fights as u,$events as e,$event_fight_table as ef,$post_meta as pm where e.ID=ef.event_id
and ef.event_fight_id=u.event_fight_id and e.post_type='bt_events' and pm.post_id = e.ID and e.post_status ='publish' and pm.meta_key='_event_dt_time' and u.`awarded_unit`!=0 and u.season_id=$season_id and u.user_id=".$user->ID."
order by pm.meta_value desc,ef.fight_order desc
) as sub
group by sub.user_id";
mysql_query("set @y=0;");
mysql_query("set @x=null;");
mysql_query("set @z=0;");
It works fine if I put order by u.primary_key. But I wants events to be sorted by date and fight order . it gives wrong result in this case.
I had checked inner query with order by statement.
for order by statement("order by pm.meta_value desc,ef.fight_order desc"
) ,it is sorting results
after calculating the best streak so it is giving wrong result.
Kindly explain how to get correct answer and what I am missing here.Thanks
Upvotes: 0
Views: 267
Reputation: 781058
You need to do the ORDER BY in a subquery, and then perform the streak detection in an outer query that processes that.
Try this (untested -- if you want me to test, supply some data in a sqlfiddle):
$sql="select sub.user_id as user_id,max(sub.streak) as streak,max(sub.units) as units
from
(
select
case when @x is null then @x:=user_id end,
case
when awarded_unit>0 and @x=user_id then @y:=@y+1
when awarded_unit<0 and @x=user_id then @y:=0
when awarded_unit>0 and @x<>user_id then @y:=1
when awarded_unit<0 and @x<>user_id then @y:=0
end as streak,
case
when awarded_unit>0 and @x=user_id then @z:=@z+awarded_unit
when awarded_unit<0 and @x=user_id then @z:=0
when awarded_unit>0 and @x<>user_id then @z:=awarded_unit
when awarded_unit<0 and @x<>user_id then @z:=0
end as units,
@x:=user_id as user_id,
awarded_unit
from (select user_id, awarded_unit
from $select_user_events_fights as u,$events as e,$event_fight_table as ef,$post_meta as pm where e.ID=ef.event_id
and ef.event_fight_id=u.event_fight_id and e.post_type='bt_events' and pm.post_id = e.ID and e.post_status ='publish' and pm.meta_key='_event_dt_time' and u.`awarded_unit`!=0 and u.season_id=$season_id and u.user_id=".$user->ID."
order by pm.meta_value desc,ef.fight_order desc) as subsub
) as sub
group by sub.user_id";
Upvotes: 1