Friday, February 25, 2011

Advanced Relation Database */ Outer Joins */

SQL OUTER JOIN 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 our SQL JOIN statement).

No comments:

Post a Comment

Classes

Programming II

Advanced Relational Database

Followers