Query two different tables in the same select

Asked

Viewed 125 times

0

I need to perform a search in two different tables and give echo in the results separately! I think it would be something more or less like this:

$consulta = "SELECT * FROM tabela1 T1 UNION (SELECT* FROM tabela2 T2)";
$con = mysqli_query ($db,$consulta);
while ($Dado = mysqli_fetch_array($con)) {
  echo $DadosT1; // Aqui resultado da primeira tabela
  echo $DadosT2; // Aqui resultado da segunda tabela
}

Can anyone enlighten me if this is possible and how it does?

  • Two different tables? when using UNION does not give, the tables must follow the same amount of fields and types ! but, which fields of Table 1 and the fields of table2?

  • There are several different fields between the two tables. Also, I needed to do this query in this way...

1 answer

1

Couldn’t you accomplish separately to achieve your goal? Something like:

$consulta = "SELECT * FROM tabela1";
$con = mysqli_query ($db,$consulta);
while ($Dado = mysqli_fetch_array($con)) {
  echo $Dado; // Aqui resultado da primeira tabela
}

$consulta = "SELECT* FROM tabela2 T2";
$con = mysqli_query ($db,$consulta);
while ($Dado = mysqli_fetch_array($con)) {
  echo $Dado; // Aqui resultado da segunda tabela
}

I’m sorry I didn’t understand your objective correctly.

  • I can, but I can’t make it work because I’m using Tabela1 to populate a table in HTML, and I need to get information from table2 to include in a column of the same table in HTML, and doing the search separately, the information in table 2 appears repeated because they are inside the while of Tabela1. Apart from all that, I still need to perform the search in the table2 according to a Tabela1 information, for example: pick the name of people according to the plate provided by Tabela1. I’m sorry, it got a little tangled, but that’s what I need to do...

  • In this case, what you need to do is perform an INNER JOIN between the tables. It is very simple to understand, gives a Google in INNER JOIN. ;)

Browser other questions tagged

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