MySQL:SUM加入有限选择行的表

时间:2013-11-06 19:01:43

标签: mysql sql join subquery correlated-subquery

我遇到类似this question的问题,但有点复杂,我无法确定如何有效地完成它。给出两个表,一个用于运动员列表,一个用于运行的比赛列表,例如,

运动员

  • ID
  • 名称
  • 性别
  • 细节

种族

  • athlete_id

我想在一段时间内按性别对所有运动员进行排名,仅使用他们的前4名比赛结果(其中“最高”由分数定义)。我觉得我应该能够在子查询中执行此操作,但我无法弄清楚如何从内部引用外部查询。我现在看起来像这样:

SELECT SUM(points) as points, a.* FROM
(SELECT rr.points, inner_a.id as athlete_id 
FROM athletes_raceresult rr 
INNER JOIN athletes_athlete inner_a ON rr.athlete_id = inner_a.id
WHERE inner_a.gender ='m' AND rr.year BETWEEN 2012 AND 2014 
AND inner_a.id = a.id
ORDER BY rr.points DESC) as races 
INNER JOIN athletes_athlete a ON races.athlete_id = a.id
GROUP BY races.athlete_id 
ORDER BY points DESC

但这不会将每个运动员的积分限制为4排。看起来我想要一个correlated subquery,但我无法让它发挥作用。

1 个答案:

答案 0 :(得分:2)

以下SQL Fiddle示例说明了如何做到这一点:

SELECT SUM(rr.points), a.id 
FROM athletes_raceresult AS rr 
INNER JOIN athletes_athlete AS a ON rr.athlete_id = a.id
WHERE (
  SELECT count(crr.points)
  FROM athletes_raceresult AS crr 
  INNER JOIN athletes_athlete AS ca ON crr.athlete_id = ca.id
  WHERE ca.gender = 'm' 
  AND crr.year BETWEEN 2012 AND 2014 
  AND crr.athlete_id = a.id AND crr.points >= rr.points
) <= 4
AND a.gender = 'm' 
AND rr.year BETWEEN 2012 AND 2014 
GROUP BY a.id