我正在运行以下查询以找到用户的最佳连胜纪录。
$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;");
如果我通过 u.primary_key 下订单,它工作正常。但我希望事件按日期和战斗顺序排序。在这种情况下它给出了错误的结果。
我已经使用 order by 语句检查了内部查询。
对于 order by statement( "order by pm.meta_value desc,ef.fight_order desc"
) ,它是在计算最佳条纹后对结果进行排序,因此它给出了错误的结果。
请解释如何获得正确答案以及我在这里缺少什么。谢谢