February 16th, 2009

INNER JOIN with Self Join

Posted by admin in L. JOINs

A self join is a normal INNER JOIN that joins one or more columns in the same table. Like any JOIN, you need two tables, but a self join means that two instances of the same table are specified.

                    Self Join syntax:                                            WHERE syntax:

        SELECT t1.column1  AS ‘title1′,                     SELECT t1.column1 AS ‘title1′,
                     t2.column1  AS ‘title2′, …                              t2.column1 AS ‘title2′, …
           FROM table1         [AS] ‘t1′                           FROM table1         [AS] ‘t1′,
          INNER JOIN table1 [AS] ‘t2′                                     table1         [AS] ‘t2′
               ON t1.column1 oper t2.column1           WHERE t1.column1 oper t2.column1
       [GROUP BY t1.column1]                               [GROUP BY t1.column1]
       [HAVING BY t1.column1]                              [HAVING BY t1.column1]
       [ORDER BY t1.column1 [ASC|DESC]]           [ORDER BY t1.column1 [ASC|DESC]]

When you are using the same column name, the column name must be qualified with the table name or alias as follows: t1.column1 oper t2.column1.

> WHERE syntax joins can only be done with AND. WHERE syntax joins using OR are not legal.

Comments are closed.

Sorry, the comment form is closed at this time.