I have a database that is modeling data similar to the kind of data you might see collected for sports. I have users and events, and users have roles at these events. Each of these events also has stats and belongs to a category, that are all currently related so:
========= ========== ============
| users | | events | | category |
|=======| |========| |==========|
| id | | id | | id |
--------- ---------- ------------
========================= =======================
| roles | | stats |
|=======================| |=====================|
| id | |id |
| user_id -> users.id | | role_id -> roles.id |
| event_id -> events.id | -----------------------
| category_id -> cat... |
-------------------------
I have been going about this trying to keep everything very well separated and normalized, but I'm starting to see a major efficiency trade off. Data is added in batches, and by a rough estimate there are about rows of stats per event, and I am pulling in hundreds of events at one time. Currently I have am toying with only one user and have 170,000 stats, and this is probably a quarter of this user's * stats.
Here's an example of how I might be querying this:
SELECT avg(some_data) FROM stats
JOIN roles ON stats.role_id = roles.id
JOIN users ON roles.user_id = roles.id
JOIN events ON roles.event_id = events.id
JOIN categories ON roles.category_id = categories.id
WHERE users.u_thing = 'something'
AND categories.name = 'something'
GROUP BY stats.timestamp
This query (on a virtual host, granted) is taking on average 8 seconds, and is performing avg() over 14000 rows.
I'm not particularly familiar with database architecture or design, so I am not sure what I can do here to optimize my schema / access pattes.
Addtional
- Caching results is a limited utility here, as new events could be added often.
- Storing precalculated statistical information would be difficult for the same reason as the previous.
- I have indexed all of the appropriate columns (pretty sure).
