If inside if inside while while inside (slow)

0

I have a question about loop while:

I have the following query :

 $sql = "SELECT id,cod,nome,cnpj,insc_estadual,tributacao FROM empresas_base WHERE tributacao = '$filtro_regime_nome' AND responsavel = '$user' GROUP BY id ORDER BY id";

This query starts a while loop, and within that loop I make another query based on the 'cod' of the company.

$sql2 = "SELECT * FROM controle_fiscal WHERE empresa = '$empresaCod' AND mes_correspondente = '$m' AND ano_correspondente = '$a' GROUP BY id ORDER BY id ";

And with that second query I make another loop while inside the previous loop to get the values I need, and on top of that second loop, there are several ifs within ifs , which causes the query to become slower than expected.

OBS: Loops and ifs are handled by functions of classe model , are not linearly arranged, but nonetheless are ifs

Doubt:

  

1 - Is it okay to do this?

     

2 - Is there another way to do this with just one query?

    
asked by anonymous 13.04.2017 / 18:18

1 answer

3

The only way to do this with a query is to use JOIN :

  

13.04.2017 / 19:52