Friday, July 4, 2008

Self-Join in SQL

when one table joins to itself, with one or two aliases to avoid confusion. A self join can be of any type, as long as the joined tables are the same.
If you have a table of members who can refer each other for services, then this might be a job for a SELF JOIN in sql where you INNER JOIN a table to itself
Syntax
CREATE PROCEDURE TestSelfJoin AS
SELECT c.custname AS 'Customer', r.custname AS 'Referrer'
FROM customers AS c
INNER JOIN customers AS r ON c.referredby=r.custnum
WHERE c.referredby<>'99999'
ORDER BY c.custname;

1 comment:

krishna said...

Hi Shaalu,
Ur post is great. I got idea about Self Join. Thanks a lot