I want to build a visual table where I can see the following things:
Team - Basketball stats about the team.
Number In League - The position that team is on each stat in the league.
League Average - The league average on each stat.
I have the following tables in my DB:
gamesstats: Have the stats on all games(what teams played and more) + link to stats table which holds all of the stat fields I want(2 links, one for the home team stat and one for the visitor team stat).
stats: Each row represents a game for one team(the stats such as 3 points attempts).
The situation is:
The "Team" row is easy to get and is fast(takes miliseconds).
The "League Average" row is easy and fast(same here).
The "Number In League" is however much slower(takes several seconds).
It is important for me that the creation won't take more than 5 seconds tops, but because I ask for the "Number In League" several times(3) in one page, it takes around 10-20 seconds.
The tables have around 100k entries.
Here is my implementation:
$p2pQuery = '100*avg(s.P2M)/avg(s.P2A)';
$p3pQuery = '100*avg(s.P3M)/avg(s.P3A)';
$ftpQuery = '100*avg(s.FTM)/avg(s.FTA)';
$effQuery = '(avg(s.TOT) + avg(s.AST) + avg(s.ST) + avg(s.PTS) + avg(s.P2M) +
avg(s.P3M) + avg(s.FTM) + avg(s.RV) + avg(s.FV)) -
(avg(s.TO) + avg(s.P3A) + avg(s.FTA) + avg(s.AG) + avg(s.CM))';
$whatWeWant = " avg(s.P2M) as P2M, avg(s.P2A) as P2A, $p2pQuery as P2P,
avg(s.P3M) as P3M, avg(s.P3A) as P3A, $p3pQuery as P3P,
avg(s.FTM) as FTM, avg(s.FTA) as FTA, $ftpQuery as FTP,
avg(s.OFFENSE) as OFFENSE, avg(s.DEF) as DEF, avg(s.TOT) as TOT,
avg(s.AST) as AST, avg(s.TO) as 'TO', avg(s.ST) as ST,
avg(s.FV) as FV, avg(s.CM) as CM, avg(s.PTS) as PTS,
$effQuery as EFF";
$allTeamsString = "SELECT t.ID as ID, $whatWeWant
FROM teams as t, gamesstats as gs, stats as s
WHERE gs.LeagueId = $ESCleague
AND gs.SeasonStart = $ESCseason
AND ((gs.HomeTeamID = t.ID AND gs.VisitorStat = s.ID)
OR (gs.VisitorTeamID = t.ID AND gs.HomeStat = s.ID))
GROUP BY t.ID";
$allTeamsQuery = MyQuery($allTeamsString);
$allTeams = resultSet2RowArray($allTeamsQuery, true);
$stat2 = array();
$stat2['Flag'] = 'In League';
//$fields holds stuff like P2M AST EFF and such as you can see in $whatWeWant
foreach($fields as $field):
$col = $field['colName'];
$counter = 1;
foreach($allTeams as $team)
if($stat1[$col] < $team[$col])
$counter++;
$stat2[$col] = $counter;
endforeach;