tags:

views:

119

answers:

5

Possible Duplicate:
sql: self-joins explained

What is self join and when would you use it? I still don't understand self joins so a Layman explanation with a example would be great.

Thank you in advance;-)

+7  A: 

You use a self join when a table references data in itself.

E.g., an Employee table may have a SupervisorID column that points to the employee that is the boss of the current employee.

To query the data and get information for both people in one row, you could self join like this:

select e1.EmployeeID, 
    e1.FirstName, 
    e1.LastName,
    e1.SupervisorID, 
    e2.FirstName as SupervisorFirstName, 
    e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID
RedFilter
+1  A: 

A self join is simply when you join a table with itself. There is no SELF JOIN keyword, you just write an ordinary join where both tables involved in the join are the same table. One thing to notice is that when you are self joining it is necessary to use an alias for the table otherwise the table name would be ambiguous.

It is useful when you want to correlate pairs of rows from the same table, for example a parent - child relationship. The following query returns the names of all immediate subcategories of the category 'Kitchen'.

SELECT T2.name
FROM category T1
JOIN category T2
ON T2.parent = T1.id
WHERE T1.name = 'Kitchen'
Mark Byers
+2  A: 

You'd use a self-join on a table that "refers" to itself - e.g. a table of employees where managerid is a foreign-key to employeeid on that same table.

Example:

SELECT E.name, ME.name AS manager
FROM dbo.Employees E
LEFT JOIN dbo.Employees ME
ON ME.employeeid = E.managerid
Will A
+5  A: 

SQL self-join simply is a normal join which is used to join a table to itself.

Example:

Select *
FROM Table t1, Table t2
WHERE t1.Id = t2.ID
Michael Pakhantsov
+2  A: 

Well, one classic example is where you wanted to get a list of employees and their immediate managers:

select e.employee as employee, b.employee as boss
from emptable e, emptable b
where e.manager_id = b.empolyee_id
order by 1

It's basically used where there is any relationship between rows stored in the same table.

  • employees.
  • multi-level marketing.
  • machine parts.

And so on...

paxdiablo
Boo for non-ANSI syntax and using ordinal in the `ORDER BY` clause rather than a column name.
RedFilter
Boo right back at you for missing the point of the answer :-) I tend to use the simplest syntax that works since the good DBMS' won't let that affect the performance.
paxdiablo