这对我来说确实是一个令人头疼的问题。本质上我有 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
感谢您的帮助! :)
最佳答案
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)
关于mysql - 比较与 ID 相关的日期和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8951932/