1

所以我有以下查询,它为组织获取活跃的竞赛,但也旨在获取领先的用户 - 对于获取的每个竞赛。

该查询当前的工作原理是它获取比赛,但是它当前获取所有用户,我想使用 SUM(activity_weight) 将获取的用户限制为 1,您可以在下面看到。

结果是这样出来的(删除了一些结果以便于查看),就我而言,我只想获取John 和 Sally,因为他们是比赛的领导者。

competitionId  compName  start_date  end_date  name  totalPoints
------------------------------------------------------------
123           First Comp   13-09-09  13-10-09  John    100
123           First Comp   13-09-09  13-10-09  Bob     50
431           Second Comp  13-05-04  13-10-05  Sally   500
431           Second Comp  13-05-04  13-10-05  Jessica 50

我知道我必须使用某种形式的子查询来使用 LIMIT,但是在确定它的语法时遇到了问题。

任何帮助深表感谢!谢谢你

  SELECT c.competitionId, c.name, c.start_date, c.end_date, a.userid, u.name, 
  u.profilePic , 
  SUM(activity_weight) AS totalPoints

  FROM activity_entries a INNER JOIN users1 u ON u.id = a.userid 
  INNER JOIN competitions c  ON c.competitionId = a.competitionId

  WHERE c.organisationId = '$organisation' AND c.start_date < now() AND c.end_date > now()  
  GROUP BY a.userid, c.competitionId ORDER BY c.id DESC, totalPoints DESC
4

1 回答 1

1

试试这个查询

select * from
(select 
@rn:=if(@prv=competitionId  , @rn+1, 1) as rId,
@prv:=competitionId  as competitionId  ,
totalPoints,
your_other_columns
from (select * from ...)subquery
join
(select @prv:=0, @rn:=0)tmp
order by 
competitionId  , totalPoints desc) a
-- only top 2 ordered by points for every competition
where rid<=2

output:
rID  competitionId  compName  start_date  end_date  name  totalPoints
------------------------------------------------------------
 1      123           First Comp   13-09-09  13-10-09  John    100
 2      123           First Comp   13-09-09  13-10-09  Bob     50
 1      431           Second Comp  13-05-04  13-10-05  Sally   500
 2      431           Second Comp  13-05-04  13-10-05  Jessica 50

将最后一部分更改where rid<=1为选择顶部 1

于 2013-09-30T07:57:26.337 回答