在我的SQL查询中编写LIMIT子查询

时间:2013-09-30 07:42:17

标签: mysql sql

所以我有一个以下的查询,它可以为一个组织取得积极的竞争,但同时也是为了获取每个竞争对手的领先用户。

查询当前的工作原理是它获取了比赛,但是它当前获取了所有用户,我想使用您可以在下面看到的SUM(activity_weight)对获取的用户进行LIMIT 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

1 个答案:

答案 0 :(得分: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