I have two tables that have the following structure:
Table 1: Show the number of tries a player has done.
Player_id, n_tries, date
Table 2: Show the number of hits a player has done.
Player_id, n_hits, date
At the end I want to have the % of hits (tries vs hits) a player has for today and the increment/decrement of hits between today and a week ago. And I would like the results to be ordered by the % of (today) hits descendent. So, for example, if we have a player with id = 1, and a player with id = 2, with this data:
Table 1:
1, 10, "2012-10-14"
2, 13, "2012-10-14"
1, 20, "2012-10-7"
2, 15, "2012-10-7"
Table 2:
1, 5, "2012-11-14"
2, 10, "2012-11-14"
1, 0, "2012-11-7"
2, 3, "2012-11-7"
I would need to finally show this:
Player_id, % hits (today), difference of hits (today vs a week ago)
2 77% +233%
1 50% +100% (actually is infinite -> (5 - 0)/0 )
I have the queries to get values from both the tables:
First table – Number of tries:
SELECT player_id, date, sum(n_tries)
FROM player_tries
WHERE (d_date = CURDATE() OR d_date = DATE_SUB(CURDATE(), INTERVAL 7 DAY))
GROUP BY date, player_id
ORDER BY player_id, date
I do a sum(n_tries) because a player can have multiple rows of tries for a particular day.
Second table – Number of hits:
SELECT player_id, date, sum(n_hits)
FROM player_hits
WHERE (d_date = CURDATE() OR d_date = DATE_SUB(CURDATE(), INTERVAL 7 DAY))
GROUP BY date, player_id
ORDER BY player_id, date
So, my question is: If from the first query I get a list of result that look like this:
Player_id, date, n_tries
1 2012-11-07 20
1 2012-11-14 10
2 2012-11-07 15
2 2012-11-14 13
And from the second table I get this:
Player_id, date, n_hits
1 2012-11-07 0
1 2012-11-14 5
2 2012-11-07 3
2 2012-11-14 10
What would be the best way to be able to mix those results and be able to have some kind of structure that is ordered by the % hits (today).?
Select hits from today and a week ago:
If you only want rows when there is a corresponding entry a week before, then replace the left join with an inner join.
The select for the tries table looks equivalent.
First select your results into arrays with
player_idas keys.You do the same with the tries table.
Now you can join the two arrays on the player_id keys: