This is really a head scratcher for me. Essentially I have 3 MySQL tables that collectively keep track of someone’s score (for a game let’s say). New scores can always be input. Essentially what I need to figure out is what players have improved their score from the past week (for this, they need to have a score before the week started AND after). Here is my table layout:
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 |
+-----------------------------------------+ +--------------------+
So essentially, from those tables, I want to have user with ID of 3 to be returned because he’s the only one that has improved his score this last week.
So far, this is where I’ve come to but I really am having trouble moving forward:
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
Thanks for your help! 🙂
1 Answer