开发者

Join this two queries into one

开发者 https://www.devze.com 2023-01-01 01:42 出处:网络
I\'m just wondering if there is a more efficient way of doing this. I have a table in which I track users scores for different flash games. The table games_scores is defined like this:

I'm just wondering if there is a more efficient way of doing this.

I have a table in which I track users scores for different flash games. The table games_scores is defined like this:

alt text http://img13.imageshack.us/img13/7262/structure1.png

Each user can have multiple entries for any game in this table. When I display the score board I only select the MAX score fore every user. Nothing fancy really.

What I'm doing then is displaying the position of the loged-in user if he is not present on the score board (the board only shows top 20 players). I've done this with two queries. The first one tells me the position of the user:

SELECT
 COUNT(*) + 1
FROM (
 SELECT
  MAX(score)
 FROM
  games_scores gs
 WHERE
  gs.games_id = ?
  AND gs.score > (
 开发者_StackOverflow中文版  SELECT
    MAX(gs2.score)
   FROM
    games_scores gs2
   WHERE
    gs2.games_id = ?
    AND gs2.users_id = ?
    AND gs2.add_time = ?
  )
  AND gs.add_time = ?
 GROUP BY
  gs.users_id
) AS tmp_table

And the second gives me his score:

SELECT
 MAX(gs.score)
FROM
 games_scores gs
WHERE
 gs.games_id = ?
 AND gs.users_id = ?
 gs.add_time >= ?

I'm wondering if there is a more efficient way of doing this? Combining the queries into one for instance.


What you're looking for is a groupwise max: http://jan.kneschke.de/projects/mysql/groupwise-max/

0

精彩评论

暂无评论...
验证码 换一张
取 消