SELF JOIN

A self join is a special type of inner join where a table is joined to itself.
They are useful when you want to find records that have values in common with other rows in the same table.
This means that the table must appear twice and therefore you must use table alias names.
In order to join a table to itself you use table aliases.
These table aliases must be used throughout the query to represent the two tables.



SELECT        C1.CompanyName 
FROM [CUSTOMERS] C1
INNER JOIN [CUSTOMERS] C2
ON C1.CustomerID = C2.CustomerID


Alternative

SELECT        C1.CompanyName 
FROM [CUSTOMERS] C1
             ,[CUSTOMERS] C2
WHERE C1.CustomerID = C2.CustomerID

This is a special type of inner join where a table is joined to itself.
This means that the table must appear twice and therefore a table alias name must be used.


ANSI Standard
This returns all employees that have a supervisor assigned to them.

SELECT       Employees.LastName, 
             Employees.FirstName,
             Supervisors.LastName,
             Supervisors.FirstName
FROM Employees
INNER JOIN Employees AS Supervisors
ON Employees.EmployeeID = Supervisors.ReportsTo

Alternative

SELECT       Employees.LastName, 
             Employees.FirstName,
             Supervisors.LastName,
             Supervisors.FirstName
FROM Employees,
             Employees Supervisors
WHERE Employees.EmployeeID = Supervisors.ReportsTo

In Access design view you can show this relationship by adding the table to the table pane twice.



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext