SQL Join Types - Exemplo de Inner Join VS Outer Join



Desenvolvido por DORNELLES Carlos Alberto - Analista de Sistemas - Brasília DF. - cad_cobol@hotmail.com

SQL Join Types - Inner Join VS Outer Join Example

Ilenia Magoni

Em um banco de dados relacional, todas as informações devem estar presentes apenas uma vez.
Mas você pode ter informações separadas em diferentes tabelas relacionadas entre si.

In a relational database, all information should only be present once.
But you might have information that's separated into different tables that's related to each other.

E você pode querer juntar essas informações relacionadas para analisar seus dados - ou seja, você pode querer juntar todos os dados (ou alguns deles).
Nesse caso, você precisará usar a instrução JOIN do SQL.
Vamos aprender como funciona.

And you might want to put this related information together to analyse its data - that is, you might want to join all the data (or some of it) together.
In this case, you'll need to use SQL's JOIN statement.
Let's learn how it works.

O que é JOIN no SQL? - What is a JOIN in SQL?

O operador JOIN permite combinar informações relacionadas de várias maneiras, conforme expliquei brevemente acima.
Existem vários tipos de junções, divididas em duas categorias principais - junções INNER e junções OUTER.

The JOIN operator lets you combine related information in various ways, as I explained briefly above.
There are various types of joins, divided into two main categories - INNER joins and OUTER joins.

A maior diferença entre INNER JOIN e OUTER JOIN é que a junção interna manterá apenas as informações de ambas as tabelas relacionadas entre si (na tabela resultante).
Uma junção externa, por outro lado, também manterá informações que não estão relacionadas à outra tabela na tabela resultante.

The biggest difference between an INNER JOIN and an OUTER JOIN is that the inner join will keep only the information from both tables that's related to each other (in the resulting table).
An Outer Join, on the other hand, will also keep information that is not related to the other table in the resulting table.

Vamos ver como INNER JOINs e OUTER JOINs funcionam em detalhes para entendê-los melhor.
Let's see how INNER JOINs and OUTER JOINs work in detail to understand them better.


Como usar um INNER JOIN no SQL - How to Use an INNER JOIN in SQL

A junção interna manterá apenas as informações das duas tabelas associadas que estão relacionadas.
Se você imaginar as duas tabelas como um diagrama de Venn , a tabela resultante de um INNER JOIN será a parte destacada em azul abaixo, onde elas se sobrepõem:

The inner join will keep only the information from the two joined tables that is related.
If you imagine the two tables as a Venn diagram, the table resulting from an INNER JOIN will be the blue highlighted part below where they overlap:

Esta é a sintaxe para uma junção interna:
Here's the syntax for an inner join:

INNER JOIN

SELECT * 
  FROM table1
  JOIN table2
    ON relation;

Veremos como isso funciona a seguir com um exemplo.
We'll see how this works below with an example.


Como usar um OUTER JOIN no SQL - How to Use an OUTER JOIN in SQL

Se você deseja manter todos os dados, e não apenas os dados relacionados entre si, você pode usar uma junção OUTER.
If you want to keep all the data, and not just the data related to each other, you can use an OUTER join.

Existem três tipos de junção externa: LEFT JOIN, RIGHT JOIN e FULL JOIN.
As diferenças entre eles envolvem quais dados não relacionados eles mantêm - pode ser da primeira tabela, da segunda ou de ambas.
As células sem dados para preencher terão um valor NULL.

There are three types of Outer Join: LEFT JOIN, RIGHT JOIN, and FULL JOIN.
The differences between them involve which unrelated data they keep - it can be from the first table, from the second, or from both of them.
The cells without data to fill will have a value of NULL.

Nota:
LEFT JOIN é o mais universalmente implementado em todas as versões do SQL.
Mas este não é o caso de RIGHT JOIN e FULL JOIN, que não são implementados em várias versões de SQL.

Note:
LEFT JOIN is the mostly universally implemented in all versions of SQL.
But this is not the case for RIGHT JOIN and FULL JOIN, which are not implemented in various SQL versions.

Vamos ver como cada um funciona individualmente.
Então, veremos como todos eles funcionam com os exemplos abaixo.

Let's see how each one works individually.
Then we'll see how they all work with examples below.


LEFT OUTER JOIN in SQL

O LEFT OUTER JOIN, ou simplesmente Left Join, manterá os dados não relacionados da tabela à esquerda (a primeira).
The LEFT OUTER JOIN, or simply Left Join, will keep the unrelated data from the left (the first) table.

Você pode imaginá-lo com um diagrama de Venn com dois círculos, com a tabela resultante sendo a parte destacada em azul que inclui a parte comum/sobreposta e o resto do círculo esquerdo.

You can imagine it with a Venn diagram with two circles, with the resulting table being the blue highlighted part which includes both the common/overlapping part, and the rest of the left circle.

A sintaxe é semelhante à abaixo.
Você verá que é semelhante à sintaxe Inner Join, mas com a palavra-chave LEFT adicionada.

The syntax looks like the below.
You'll see that it is similar to the Inner Join syntax, but with the LEFT keyword added.

LEFT OUTER JOIN

SELECT columns
  FROM table1
  LEFT JOIN table2
    ON relation;

RIGHT OUTER JOIN in SQL

O RIGHT OUTER JOIN, ou simplesmente Right Join, manterá os dados da segunda tabela que não estão relacionados à primeira.
The RIGHT OUTER JOIN, or simply Right Join, will keep the data in the second table that's not related to the first table.

Você pode imaginá-lo com um diagrama de Venn com dois círculos, com a tabela resultante sendo a parte destacada em azul que inclui a parte sobreposta e o resto do círculo direito.

You can imagine it with a Venn diagram with two circles, with the resulting table being the blue highlighted part which includes both the overlapping part, and the rest of the right circle.

A sintaxe é a seguinte, a única diferença é a palavra-chave RIGHT.
The syntax is as below, the only difference is the RIGHT keyword.

RIGHT OUTER JOIN

SELECT columns
  FROM table1
 RIGHT JOIN table2
    ON relation;

FULL OUTER JOIN in SQL

Você pode pensar em FULL OUTER JOIN como a combinação de uma junção à esquerda e uma junção à direita.
Ele manterá todas as linhas de ambas as tabelas e os dados ausentes serão preenchidos com NULL.

You can think of the FULL OUTER JOIN as the combination of a Left Join and Right Join.
It will keep all rows from both tables, and the missing data will be filled in with NULL.

Você pode imaginá-lo com um diagrama de Venn com dois círculos, com a tabela resultante sendo a parte destacada em azul que inclui tudo: a parte sobreposta, o círculo esquerdo e o círculo direito.

You can imagine it with a Venn diagram with two circles, with the resulting table being the blue highlighted part which includes everything: the overlapping part, the left circle, and the right circle.

Representação do diagrama de Venn para Full Outer Join
Venn diagram representation for Full Outer Join

A sintaxe é a seguinte, usando a palavra-chave FULL.
The syntax is as below, using the FULL keyword.

FULL OUTER JOIN

SELECT columns
  FROM table1
  FULL JOIN table2
    ON relation;

Exemplos de operador SQL JOIN - Examples of SQL JOIN operator

Um possível banco de dados para uma clínica veterinária poderia ter uma tabela para animais de estimação e outra para os proprietários.
Como um proprietário pode ter vários animais de estimação, a tabela de animais de estimação terá uma coluna owner_id que aponta para a tabela de proprietários.

A possible database for a vet clinic could have one table for pets and one for the owners.
Since an owner could have multiple pets, the pets table will have an owner_id column that points to the owners table.

Tabela animais de estimação - Pets table
id name age owner_id
1 Fido 7 1
2 Missy 3 1
3 Sissy 10 2
4 Copper 1 3
5 Hopper 2 0
Tabela dos proprietários - Owners table
id name phone_number
1 Johnny 4567823
2 Olly 7486513
3 Ilenia 3481365
4 Luise 1685364

Você pode usar uma consulta simples para obter uma tabela com o nome do animal de estimação e o nome do proprietário próximos um do outro.
Vamos fazer isso com todos os diferentes operadores JOIN.

You could use simple query to get a table with the pet name and the owner name next to each other.
Let's do it with all the different JOIN operators.


Exemplo de SQL INNER JOIN - SQL INNER JOIN example

Vamos fazer isso primeiro usando JOIN.
Let's do it first using JOIN.

Neste caso, você deve SELECIONAR o nome da coluna da tabela de animais de estimação (e renomeá-la como pet_name).
Em seguida, você selecionaria a coluna de nome da tabela de proprietários e a renomearia como proprietário.
Isso ficaria assim: SELECT pets.name AS pet_name, owners.name AS owner.

In this case you would SELECT the column name from the pets table (and rename it pet_name).
Then you would select the name column from the owners table, and rename it owner.
That would look like this: SELECT pets.name AS pet_name, owners.name AS owner.

Você usaria FROM para dizer que as colunas são da tabela de pets e JOIN para dizer que deseja juntá-la com a tabela de proprietários, usando esta sintaxe: FROM pets JOIN owner.

You would use FROM to say that the columns are from the pets table, and JOIN to say that you want to join it with the owners table, using this syntax: FROM pets JOIN owner.

E, finalmente, você diria que deseja juntar duas linhas quando a coluna owner_id na tabela pets for igual à coluna id na tabela owner com ON pets.owner_id = owners.id.

And finally you would say that you want to join two rows together when the owner_id column in the pets table is equal to the id column in the owner table with ON pets.owner_id = owners.id.

Aqui está tudo junto:
Here it is all together:

SELECT pets.name AS pet_name
,      owners.name AS owner
  FROM pets
  JOIN owners
    ON pets.owner_id = owners.id;

Você obteria uma tabela como a abaixo, onde apenas os animais de estimação conectados ao dono e os proprietários conectados a um animal de estimação estão incluídos.
You would get a table as below, where only the pets connected to an owner and the owners connected to a pet are included.

pet_name owner
Fido Johnny
Missy Johnny
Sissy Olly
Copper Ilenia

Exemplo de SQL LEFT JOIN - SQL LEFT JOIN example

Vamos fazer a mesma consulta usando LEFT JOIN para que você possa ver a diferença.
A consulta é a mesma, exceto adicionar a palavra-chave LEFT.

Let's do the same query using LEFT JOIN so you can see the difference.
The query is the same other than adding the LEFT keyword.

SELECT pets.name AS pet_name
,      owners.name AS owner
  FROM pets
  LEFT JOIN owners
    ON pets.owner_id = owners.id;

Neste caso, as linhas da tabela da esquerda, pets, são todas mantidas e, quando faltam dados vindos da tabela dos proprietários, eles são preenchidos com NULL.
In this case the rows from the left table, pets, are all kept, and when there is data missing coming from the owners table, it is filled with NULL.

pet_name owner
Fido Johnny
Missy Johnny
Sissy Olly
Copper Ilenia
Hopper NULL

Parece que há um animal de estimação que não está registrado no proprietário.
It seems there is a pet that is not registered with an owner.


Exemplo de SQL RIGHT JOIN - SQL RIGHT JOIN example

Se você fizer a mesma consulta usando RIGHT JOIN, obterá um resultado diferente.
If you do the same query using RIGHT JOIN you would get yet a different result.

SELECT pets.name AS pet_name
,      owners.name AS owner
  FROM pets
 RIGHT JOIN owners
    ON pets.owner_id = owners.id;

Neste caso, todas as linhas da tabela certa, proprietários, são mantidas e, se houver um valor ausente, ele será preenchido com NULL.
In this case all the rows from the right table, owners, are kept, and if there is a missing value, it is filled with NULL.

pet_name owner
Fido Johnny
Missy Johnny
Sissy Olly
Copper Ilenia
NULL Louise

Parece que há um dono que não tem um animal de estimação cadastrado.
It seems there is an owner that does not have a pet registered.


Exemplo de SQL FULL JOIN - SQL FULL JOIN example

Você poderia fazer a mesma consulta novamente, usando FULL JOIN.
You could do the same query again, using FULL JOIN.

SELECT pets.name AS pet_name
,      owners.name AS owner
  FROM pets
  FULL JOIN owners
    ON pets.owner_id = owners.id;

A tabela resultante é novamente diferente - neste caso, todas as linhas das duas tabelas são mantidas.
The resulting table is again different - in this instance all rows from the two tables are kept.

pet_name owner
Fido Johnny
Missy Johnny
Sissy Olly
Copper Ilenia
Hopper NULL
NULL Louise

Parece que existe um animal de estimação sem dono e um dono sem animal de estimação em nosso banco de dados.
It seems that there is a pet without an owner and an owner without a pet in our database.


Conclusão - Conclusion:

Em um banco de dados relacional, todos os dados devem ser gravados apenas uma vez.
Para então analisar esses dados, você precisa de algo para juntar os dados relacionados.

In a relational database, all data should be written only once.
To then analyse this data you need something to join the related data together.

Neste artigo, você aprendeu como usar o operador JOIN para fazer isso.
Espero que seja útil para você, divirta-se!

In this article, you have learned how to use the JOIN operator to do so.
I hope it will be useful for you, have fun!

Leia também:



© Copyright www.freecodecamp.org