Thursday, 29 August 2013

Many (many) SQL JOINs vs Multiple queries

Many (many) SQL JOINs vs Multiple queries

I'm here to ask a question that many of you have already ask yourselves, I
suppose. I am creating a PHP website, and everything has been running
smoothly until I decided to populate my database with some test data (real
data, which when the application starts being used for real, is going to
be even bigger). Most of the things still work fine, but one particular
(and really important) feature started having execution times of three to
four seconds, and most of these time is spent in the MySQL server.
Here's the deal: I'm building an application for a school, and it needs to
have all the schedules and lessons for every day, every person, every
room, every class. The structure of the database is done, the indexes are
created, etc... The problem is that since all this data is relational (and
can be spread across many tables) one query to get them all might look
like this:
SELECT field1, field2, etc
FROM schedules AS su
LEFT JOIN schedules_lessons AS sul
ON sul.ID_SCHEDULE = su.ID
LEFT JOIN schedules_lessons_teachers AS sult
ON sult.ID_LESSON = sul.ID
LEFT JOIN users AS u
ON u.ID = sult.ID_TEACHER
LEFT JOIN schedules_periods AS sup
ON sup.ID_SCHEDULE = su.ID
LEFT JOIN schedules_periods AS sulp
ON sulp.ID_SCHEDULE = sul.ID_SCHEDULE AND sulp.period = sul.period
LEFT JOIN schools AS s
ON s.ID = su.ID_SCHOOL
LEFT JOIN schools_buildings AS sb
ON sb.ID_SCHOOL = s.ID
LEFT JOIN schools_rooms AS sr
ON sr.ID = sul.ID_ROOM
LEFT JOIN schools_classes AS sc
ON sc.ID = sul.ID_CLASS
Yeah, that's a lot of joins, I know. My question is: how should I get the
best balance between the number of joins & the number or queries? Because
I feel like this could be really improved, but I'm not sure how to achieve
it.

No comments:

Post a Comment