数据库查询相关问题

时间:2014-05-27 19:03:53

标签: mysql sql codeigniter

我有一张表格如下

id  contest_id rank score   team_id
449 59          3   80      26
478 60         13   44      26
647 63          1   99      26
574 79         29   18      29
579 79          7   57      38
608 62         33   18      43
530 73          3   85      53
482 60          8   51      56
654 63          4   79      56
456 59          6   67      56
541 73          6   72      56

现在我想通过总和(得分)按team_id顺序选择每个团队组的前5个得分总和

现在我正在使用此查询,它无法以各种方式工作

SELECT team_id as team, sum( score ) as score
FROM contest_result_pk
WHERE (
  SELECT COUNT( * )
  FROM contest_result_ck AS c
  WHERE c.team_id = contest_result_pk.team_id
  AND contest_result_pk.score <= c.score
) <= 5
GROUP BY team_id
ORDER BY sum( score) DESC

1 个答案:

答案 0 :(得分:2)

对于这么简单的事情来说,这太复杂了......

SELECT team_id, SUM(score) AS score
FROM contest_result_pk
GROUP BY team_id
ORDER BY score DESC
LIMIT 5