How to display 2 columns of 2 different tables in MySQL?

Posted on

Question :

I have 2 tables with several columns.

I would like you to display individual columns from more than one table at a time:

tabela1 | tabela2

Nome    | Apelido


Answer :

There is not much secret:

SELECT tabela1.nome, tabela2.apelido FROM tabela1, tabela2;

After SELECT you will place the list of columns you want displayed. When you have more than one table it is important to qualify the column completely, that is, tell which table the column belongs, in other words, give it a surname, so it becomes more obvious where this column comes from and avoid ambiguity if the tables columns with the same name. In some cases the name of the table can be omitted but it is usually interesting to put it anyway.

Then the FROM clause lists all the tables that should be available in the query. Without this you will not be able to use them for all operations. It is possible to create a nickname for the table name as demonstrated in another answer but it is not relevant for what you want. It’s just a convenience when you’ll often use the table name.


Assuming you have a table1 with the following fields:

-Id - Integer
-Nomes - String
-IdTabela2 - Integer

and a Table2 with the following fields:

-Id - Integer
-Apelidio - String

We run the following query:

SELECT t1.Nome, t2.Apelido
FROM Tabela1 AS t1, Tabela2 AS t2
WHERE t1.IdTabela2 ==

In the third line WHERE t1.IdTabela2 == says that “where Table2 column of Table1 is equal to the column ID of table2”, thus occurring the relationship between the two tables, that is, query will present all the names with their respective nicknames that are related through foreign key IdTabela2 , I hope you have given to understand.


Simple like this:



And when you have a select using inner join and you want to go through multiple tables to display. Example:

id – racialosocial – common – opme
                   58 89

In this example “Common” is a select traversing X tables and “Opme” is another select traversing X tables, both of which pass through tables that have the racial field. With such an example I do not know how to structure to display information. I’ve tried using subselect and union all, but it did not work. With union all I can show the information but they stay in the common field and this is not what I want to display column next to column.


Leave a Reply

Your email address will not be published. Required fields are marked *