比较与ID相关的日期和值

时间:2012-01-21 09:23:52

标签: mysql

这对我来说真是个蠢货。基本上我有3个MySQL表,共同记录某人的得分(对于一个游戏让我们说)。始终可以输入新分数。基本上我需要弄清楚的是,球员们在过去一周内的得分有所提高(为此,他们需要在本周开始前和之后得分)。这是我的表格布局:

   USER                   REQUEST (ASSOCIATIVE TABLE)                   SCORE
+----------+    +-----------------------------------------+       +--------------------+
| id (int) |    | id  |    user_id   |    date (UNIX TS)  |       | request_id | score |
+----------+    +-----------------------------------------+       +--------------------+
|    3     |    |  1  |      3       |    before week     |       |     1      |  10   |
|    4     |    |  2  |      3       |    after week      |       |     2      |  20   |
|    5     |    |  3  |      4       |    before week     |       |     3      |  5    |
+----------+    |  4  |      5       |    after week      |       |     4      |  15   |
                +-----------------------------------------+       +--------------------+

基本上,从那些表中,我想要返回ID为3的用户,因为他是唯一一个在上周提高了他的分数的人。

到目前为止,这是我来的地方,但我真的遇到了麻烦:

SELECT user.id AS user_id, score, count(*) AS n 
FROM user 
LEFT JOIN request ON request.user_id = user.id 
LEFT JOIN score ON score.request_id = request.id WHERE request.date > (WEEK UNIX TS) 
GROUP BY user_id HAVING n > 1 
ORDER BY request.date DESC

感谢您的帮助! :)

1 个答案:

答案 0 :(得分:1)

SELECT user.id             AS user_id
     , MAX(sc_now.score)   AS score_now
     , MAX(sc_prev.score)  AS score_previous

FROM user 

  JOIN request AS req_now
    ON  req_now.user_id = user.id 
    AND req_now.date > (WEEK UNIX TS)    --- condition for this week 
  JOIN score AS sc_now
    ON sc_now.request_id = req_now.id 

  JOIN request AS req_prev
    ON  req_prev.user_id = user.id 
    AND req_prev.date BETWEEN ? AND ?    --- condition for previous week
  JOIN score AS sc_prev
    ON sc_prev.request_id = req_prev.id 

GROUP BY user.id

HAVING MAX(sc_now.score) > MAX(sc_prev.score)