Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How far should I go to minimize database queries?

Tags:

php

mysql

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?

like image 400
Steven Sokulski Avatar asked Jul 30 '12 14:07

Steven Sokulski


People also ask

How often should you query a database?

It just depends. You can query your database as often as you can, however you may meet efficiency issue. You can just write a script which just query your database and set a clock to make that script just run for sometime (30 seconds for example). You count the total query, and output the count into file.

How long should a SQL query take?

The query takes 20 to 500 ms (or sometimes more) depending on the system and the amount of data. The performance of the database or the database server has a significant influence on the speed.


1 Answers

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.

like image 153
ametren Avatar answered Oct 20 '22 12:10

ametren