Blogia
MeSeminary

Funcionamiento de "JOIN"

Definicion: 

La sentencia join en SQL permite combinar registros de dos o más tablas en una base de datos relacional. En el Lenguaje de Consultas Estructurado (SQL), hay tres tipo de JOIN: interno, externo, y cruzado.

En casos especiales una tabla puede unirse a sí misma, produciendo una auto-combinación, SELF-JOIN.

Matemáticamente, JOIN es composición relacional, la operación fundamental en el álgebra relacional, y generalizando es una función de composición.

 

Ejemplo:

 

Customers:

CustomerIDFirstNameLastNameEmailDOBPhone
1JohnSmithJohn.Smith@yahoo.com2/4/1968626 222-2222
2StevenGoldfishgoldfish@fishhere.net4/4/1974323 455-4545
3PaulaBrownpb@herowndomain.org5/24/1978416 323-3232
4JamesSmithjim@supergig.co.uk20/10/1980416 323-8888

 

Sales:


CustomerIDDateSaleAmount
25/6/2004$100.22
15/7/2004$99.95
35/7/2004$122.95
35/13/2004$100.00
45/22/2004$555.55

As you can see those 2 tables have common field called CustomerID and thanks to that we can extract information from both tables by matching their CustomerID columns.

Consider the following SQL statement:


SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer
FROM Customers, Sales
WHERE Customers.CustomerID = Sales.CustomerID
GROUP BY Customers.FirstName, Customers.LastName 

The SQL expression above will select all distinct customers (their first and last names) and the total respective amount of dollars they have spent. 
The SQL JOIN condition has been specified after the SQL WHERE clause and says that the 2 tables have to be matched by their respective CustomerID columns.

Here is the result of this SQL statement:

FirstNameLastNameSalesPerCustomers
JohnSmith$99.95
StevenGoldfish$100.22
PaulaBrown$222.95
JamesSmith$555.55

The SQL statement above can be re-written using the SQL JOIN clause like this:


SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer
FROM Customers JOIN Sales
ON Customers.CustomerID = Sales.CustomerID
GROUP BY Customers.FirstName, Customers.LastName 

There are 2 types of SQL JOINS – INNER JOINS and OUTER JOINS. If you don't put INNER or OUTER keywords in front of the SQL JOIN keyword, then INNER JOIN is used. In short "INNER JOIN" = "JOIN" (note that different databases have different syntax for their JOIN clauses).

The INNER JOIN will select all rows from both tables as long as there is a match between the columns we are matching on. In case we have a customer in the Customers table, which still hasn't made any orders (there are no entries for this customer in the Sales table), this customer will not be listed in the result of our SQL query above.

If the Sales table has the following rows:

CustomerIDDateSaleAmount
25/6/2004$100.22
15/6/2004$99.95

And we use the same SQL JOIN statement from above:


SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer
FROM Customers JOIN Sales
ON Customers.CustomerID = Sales.CustomerID
GROUP BY Customers.FirstName, Customers.LastName 

We'll get the following result:

FirstNameLastNameSalesPerCustomers
JohnSmith$99.95
StevenGoldfish$100.22

Even though Paula and James are listed as customers in the Customers table they won't be displayed because they haven't purchased anything yet.

But what if you want to display all the customers and their sales, no matter if they have ordered something or not? We’ll do that with the help of SQL OUTER JOIN clause.

The second type of SQL JOIN is called SQL OUTER JOIN and it has 2 sub-types called LEFT OUTER JOIN and RIGHT OUTER JOIN.

The LEFT OUTER JOIN or simply LEFT JOIN (you can omit the OUTER keyword in most databases), selects all the rows from the first table listed after the FROM clause, no matter if they have matches in the second table.

If we slightly modify our last SQL statement to:


SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer
FROM Customers LEFT JOIN Sales
ON Customers.CustomerID = Sales.CustomerID
GROUP BY Customers.FirstName, Customers.LastName 

and the Sales table still has the following rows:

CustomerIDDateSaleAmount
25/6/2004$100.22
15/6/2004$99.95

The result will be the following:

FirstNameLastNameSalesPerCustomers
JohnSmith$99.95
StevenGoldfish$100.22
PaulaBrownNULL
JamesSmithNULL

As you can see we have selected everything from the Customers (first table). For all rows from Customers, which don’t have a match in the Sales (second table), the SalesPerCustomer column has amount NULL (NULL means a column contains nothing).

The RIGHT OUTER JOIN or just RIGHT JOIN behaves exactly as SQL LEFT JOIN, except that it returns all rows from the second table (the right table in ourSQL JOIN statement).

 

0 comentarios