Optimize SQL Query in three tables

Asked

Viewed 149 times

1

I have a product table that has a foreign key that is the category and a table that stores the name of the product photos. I usually make two queries: one to retrieve the category name and some product fields and another to collect an image of the product. In the product consultation I have:

$consultaProdutos = $_db->select("SELECT c.categoria, p.idproduto,  p.nome, p.valor FROM categoria AS c, produto as p WHERE p.ativo = 1 AND p.idcategoria = c.idcategoria");

The other consultation I perform within the result of the first consultation being it:

foreach ($consultaProdutos as $key => $rowProduto) {
        $consultaFoto = $_db->select("SELECT * FROM foto_produto WHERE idproduto = :idproduto LIMIT 1", array(':idproduto' => $rowProduto->idproduto ));
        $fotoProduto = $consultaFoto[0];
//html aqui

Where in the variable $fotoProduct there is the result of the query by the photo. However I believe it will be more efficient if there is only one query.

1 answer

2


In hand:

SELECT
    c.categoria,
    p.idproduto,
    p.nome,
    p.valor,
    fp.*
FROM
    categoria AS c,
    produto AS p,
    foto_produto AS fp
WHERE p.ativo = 1
AND p.idcategoria = c.idcategoria
AND fp.idproduto = p.idproduto

Don’t forget to replace fp.* by the columns you will really need to increase the performance of the query.

In this case you will have several rows with the same table value categoria and produto, but with different values on account of the table foto_produto.

Another idea is to group the values of the tables categoria and produto and use the function GROUP_CONCAT to return the photos in a single string.

  • The problem with your solution is that it will repeat the result of the product so often exist images for it; that is, if there are 10 images for the same product, it will be displayed 10 times.

  • Yes, it is important to check the repeated values to display them once while iterating through the product photos. So I gave several ideas on how to treat the resultset.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.