Here's a description of the data I'm going to pull from a MySQL database for a product page on a current project.
Product data comes from a product
table, variable names (color, size, etc.) come from a table called product_option_group
, the actual values for those variables (red, green, blue or small, medium, large, etc.) are in a product_option
table, and product photos associated with that product are in product_photo
.
I could probably use JOIN
-s to create a single query that returns all of that (product, variables, values, photos) in a single query that I would then need to foreach
the hell out of to make useful. My question is whether or not that makes any sense. To what extent should I work to minimize queries?
In the case of a list of products I'm using a single query to fetch the small amount of product data and the URL of the first product photo. But on a page showing a single product, I'm a little unsure as to the best approach. Seems like one way I'm writing a crazy long MySQL query and then doing a lot of PHP parsing. And another way I'm making a fistful of database calls.
Which is best?
I've always been taught (and worked with) the assumption that you should only optimize when needed, and not try to optimize things that aren't causing problems.
So, in your case, take what you've got and run it through the mill -- put a load on it and see how it handles it. If it's slow, then think about whether you want to try to combine into one query, or add an index or two, or what you might do to speed it up. Ask yourself if it's the DB which is returning slowly, or if the traffic back and forth between the two is the problem, or if the PHP is not processing it fast enough for you.
Spend your time where it is needed, and remember to keep it simple.
It is good practice to minimize the number of queries per page load.
However, database servers are good at dealing with many small queries. A lot of CMS's have hundreds of queries per page load.
So, always try to optimize but don't go crazy with it.