Reputation: 1
I have the tables Tabela A
, Tabela B
, Tabela C
. I want the result on table Consulta
:
Tabela A Tabela B
---------------------------------
ID_A | Cidade ID_B | Cidade
---------------------------------
1 | Porto 1 | Preto
2 | Braga 2 | Verde
3 | Lisboa 3 | Amarelo
4 | Coimbra 4 | Branco
Tabela C
-------------------
ID_C | ID_A | ID_B
-------------------
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 2 | 2
5 | 2 | 3
6 | 2 | 4
7 | 3 | 2
8 | 3 | 3
9 | 4 | 1
10 | 4 | 3
11 | 4 | 4
Tabela Consulta
-----------------------------------------------
ID_C | Cidade | Cor
-----------------------------------------------
1 | Porto | Preto; Verde;
2 | Braga | Preto; Verde; Amarelo; Branco
3 | Lisboa | Verde; Amarelo;
4 | Coimbra | Preto; Amarelo; Branco;
I have the solution but is to slow because i have 15 000 records to show. Can anyone hep me improve the time, or give me another solution.
<? php
$sql1 = "SELECT * FROM tabela_a order by id ASC";
$resultado = mysql_db_query($database, $sql1);
while ($registo = mysql_fetch_array($resultado)) {
$id_a = $registo["id"];
$cidade = $registo['cidade'];
echo $id_a; ?> : <? php
echo $cidade; ?> : <? php
$sql2 = "SELECT id_b FROM tabela_c where id_a=$id_a";
$resultado2 = mysql_db_query($database, $sql2);
$quantreg = mysql_num_rows($resultado2);
$i = 0;
while ($i < $quantreg) {
$registo2 = mysql_fetch_array($resultado2) or die(mysql_error());
$id_b = $registo2["id_b"];
$sql3 = "select * from tabela_b where id=$id_b";
$resultado3 = mysql_db_query($database, $sql3);
$registo3 = mysql_fetch_array($resultado3) or die(mysql_error());
$cor = $registo3["cor"];
echo $cor."; ";
$i++;
}
?>
</br>
<?php
}
?>
Upvotes: 0
Views: 51
Reputation: 1269743
This is just join
and group by
. You should do all the work in a single query:
select a.id_a, a.Cidade, group_concat(b.cor separator '; ') as cor
from c join
a
on a.id_a = c.id_a join
b
on b.id_b = c.id_b
group by a.id_a, a.Cidade
order by a.id_a;
Note: I'm guessing the column in table b
is really called cor
and not cidade
.
Upvotes: 1