Self-joins

It is possible to join a table with itself. This is called self-join. Self-join has no special syntax. In fact, all the data sources in a query are independent even though they could be the same physically. Suppose one wants to know about each record of the table a and how many records exist with a bigger value than the field a_int. The following query can be used for this:

car_portal=> SELECT t1.a_int AS current, t2.a_int AS bigger
FROM car_portal_app.a t1
INNER JOIN car_portal_app.a t2 ON t2.a_int > t1.a_int;
current | bigger
--------+--------
1 | 2
1 | 3
2 | 3
(3 rows)

The table a is joined to itself. From the logic of the query, it does not matter if two different tables are joined or if the same table is used twice. To be able to reference the fields and distinguish the instances of the table, the table aliases are used. The first instance is called t1 and the second t2. From the results, it is visible that for the value 1 there are two bigger values: 2 and 3; and for the value 2 only one bigger value exists which is 3. The examined value is in the column named current and the bigger values are in the column called bigger.

The value 3 is not selected because there are no values bigger than 3. However, if one wants to explicitly show that, LEFT JOIN is used:

car_portal=> SELECT t1.a_int AS current, t2.a_int AS bigger
FROM car_portal_app.a t1
LEFT JOIN car_portal_app.a t2 ON t2.a_int > t1.a_int;
current | bigger
--------+--------
1 | 2
1 | 3
2 | 3
3 |
(4 rows)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset