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

4

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
    
asked by anonymous 10.07.2015 / 19:35

4 answers

10

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.

    
10.07.2015 / 19:37
2

Assuming you have a table1 with the following fields:

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

and a Table2 with the following fields:

Tabela2
-Id - Integer
-Apelidio - String

We run the following query:

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

In the third line WHERE t1.IdTabela2 == t2.id 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.

    
10.07.2015 / 19:43
1

Simple like this:

SELECT
  'tabela1'.'Nome',
  'tabela2'.'Apelido'
FROM
  'tabela1',
  'tabela2';
    
10.07.2015 / 19:37
-1

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.

    
27.01.2017 / 13:52