MySQL - 为具有不同条件的组中的每一行获取count()

时间:2012-07-31 11:23:41

标签: mysql

我有一个高分表scores: (id int, deviceid int, value int, board int)。 我想为特定玩家展示一个位置。目前我正在这样做(在PHP中):

我选择了玩家得分和得分的所有棋盘:

select board, min(value) as value
from scores
where deviceid = 1234
group by board

然后对于每一行($ board,$ value),我选择:

select count(id) from scores
where board = $board and value < $value

通过选择得分低于指定值的特定棋盘的行数,我得到玩家的位置(第一个玩家将获得位置0,因此在显示时将增加1)

我知道这是非常无效的,所以我正在寻找一种方法来更快地完成。它可以在带有光标的存储过程中完成,但对于100个板,我需要做最多1 + 100次选择。

我简而言之,我想在伪sql中执行类似的操作:

select board, min(value) as val,
       count(id) from _this_group_ where value < val
from scores
where deviceid = 1234
group by board

2 个答案:

答案 0 :(得分:2)

SELECT scores.board, count(1) AS position
FROM scores
JOIN
  (SELECT board, MIN(value) AS value
   FROM scores
   WHERE deviceid = 1234
   GROUP BY board
  ) player_scores
ON scores.board = player_scores.board
WHERE scores.value < player_scores.value
GROUP BY scores.board

答案 1 :(得分:0)

您可以尝试以下内容:

SELECT a.board, b.val COUNT(1) AS cnt
FROM scores a
    INNER JOIN(
        SELECT board, MIN(value) as val
        FROM scores
        WHERE deviceid = 1234
        GROUP BY board
    ) b
     ON a.board = b.board
    AND a.value < b.val
WHERE a.deviceid = 1234
GROUP BY a.board;

SELECT a.board, MIN(a.value) as val,
       (SELECT COUNT(1)
        FROM scores b
        WHERE b.board = a.board AND
        b.value < MIN(a.value)) AS cnt
FROM scores a
WHERE a.deviceid = 1234;