3.2. JOINING TABLES 21
SELECT T1.attr, T2.attr, T3.attr
FROM table_name1 T1
INNER JOIN table_name2 T2 ON T1.keyid = T2.keyid
INNER JOIN table_name3 T3 ON T1.keyid = T3.keyid;
3.2.4 Self join
In this section, we will use the table that results from the cross join between T1 and T2 as
shown in Figure 3.2.3. We will label the cross joined table as CJ, the ID from T1 as ID1 and
the ID from T2 as ID2. A self join will join an attribute with itself, generally with a specific
filtering in mind. For example, if we have a table named people that stores what city a
given person is in, along with their name, we can SELECT people from the same city using a
self join technique that requires creating a copy of the table. If we want to use self join on
our table, CJ, where we are looking to combine all the attributes that have ID1 = ID2 and
ID1 <> ID2, then we can use the self join that follows.
SELECT *
FROM CJ cj1
INNER JOIN CJ cj2
on (cj1.id1 = cj2.id1) and (cj1.id2 <> cj2.id2)
[(1, 4, ‘a’, ‘v’, 1, 5, ‘a’, ‘w’),
(1, 4, ‘a’, ‘v’, 1, 6, ‘a’, ‘x’),
(1, 4, ‘a’, ‘v’, 1, 7, ‘a’, ‘y’),
(1, 4, ‘a’, ‘v’, 1, 8, ‘a’, ‘z’),
(1, 5, ‘a’, ‘w’, 1, 4, ‘a’, ‘v’),
(1, 5, ‘a’, ‘w’, 1, 6, ‘a’, ‘x’),
(1, 5, ‘a’, ‘w’, 1, 7, ‘a’, ‘y’),
(1, 5, ‘a’, ‘w’, 1, 8, ‘a’, ‘z’),
(1, 6, ‘a’, ‘x’, 1, 4, ‘a’, ‘v’),
(1, 6, ‘a’, ‘x’, 1, 5, ‘a’, ‘w’),
(1, 6, ‘a’, ‘x’, 1, 7, ‘a’, ‘y’),
(1, 6, ‘a’, ‘x’, 1, 8, ‘a’, ‘z’),
(1, 7, ‘a’, ‘y’, 1, 4, ‘a’, ‘v’),
(1, 7, ‘a’, ‘y’, 1, 5, ‘a’, ‘w’),
(1, 7, ‘a’, ‘y’, 1, 6, ‘a’, ‘x’),
(1, 7, ‘a’, ‘y’, 1, 8, ‘a’, ‘z’),
(1, 8, ‘a’, ‘z’, 1, 4, ‘a’, ‘v’),
(1, 8, ‘a’, ‘z’, 1, 5, ‘a’, ‘w’),
(1, 8, ‘a’, ‘z’, 1, 6, ‘a’, ‘x’),
(1, 8, ‘a’, ‘z’, 1, 7, ‘a’, ‘y’),
...
(5, 4, ‘e’, ‘v’, 5, 5, ‘e’, ‘w’),
(5, 4, ‘e’, ‘v’, 5, 6, ‘e’, ‘x’),
(5, 4, ‘e’, ‘v’, 5, 7, ‘e’, ‘y’),
(5, 4, ‘e’, ‘v’, 5, 8, ‘e’, ‘z’),
(5, 5, ‘e’, ‘w’, 5, 4, ‘e’, ‘v’),
(5, 5, ‘e’, ‘w’, 5, 6, ‘e’, ‘x’),
(5, 5, ‘e’, ‘w’, 5, 7, ‘e’, ‘y’),
(5, 5, ‘e’, ‘w’, 5, 8, ‘e’, ‘z’),
(5, 6, ‘e’, ‘x’, 5, 4, ‘e’, ‘v’),
(5, 6, ‘e’, ‘x’, 5, 5, ‘e’, ‘w’),
(5, 6, ‘e’, ‘x’, 5, 7, ‘e’, ‘y’),
(5, 6, ‘e’, ‘x’, 5, 8, ‘e’, ‘z’),
(5, 7, ‘e’, ‘y’, 5, 4, ‘e’, ‘v’),