]> begriffs open source - ai-pg/blob - full-docs/txt/tutorial-join.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / tutorial-join.txt
1
2 2.6. Joins Between Tables #
3
4    Thus far, our queries have only accessed one table at a time. Queries
5    can access multiple tables at once, or access the same table in such a
6    way that multiple rows of the table are being processed at the same
7    time. Queries that access multiple tables (or multiple instances of the
8    same table) at one time are called join queries. They combine rows from
9    one table with rows from a second table, with an expression specifying
10    which rows are to be paired. For example, to return all the weather
11    records together with the location of the associated city, the database
12    needs to compare the city column of each row of the weather table with
13    the name column of all rows in the cities table, and select the pairs
14    of rows where these values match.^[4] This would be accomplished by the
15    following query:
16 SELECT * FROM weather JOIN cities ON city = name;
17
18      city      | temp_lo | temp_hi | prcp |    date    |     name      | locatio
19 n
20 ---------------+---------+---------+------+------------+---------------+--------
21 ---
22  San Francisco |      46 |      50 | 0.25 | 1994-11-27 | San Francisco | (-194,5
23 3)
24  San Francisco |      43 |      57 |    0 | 1994-11-29 | San Francisco | (-194,5
25 3)
26 (2 rows)
27
28    Observe two things about the result set:
29      * There is no result row for the city of Hayward. This is because
30        there is no matching entry in the cities table for Hayward, so the
31        join ignores the unmatched rows in the weather table. We will see
32        shortly how this can be fixed.
33      * There are two columns containing the city name. This is correct
34        because the lists of columns from the weather and cities tables are
35        concatenated. In practice this is undesirable, though, so you will
36        probably want to list the output columns explicitly rather than
37        using *:
38 SELECT city, temp_lo, temp_hi, prcp, date, location
39     FROM weather JOIN cities ON city = name;
40
41    Since the columns all had different names, the parser automatically
42    found which table they belong to. If there were duplicate column names
43    in the two tables you'd need to qualify the column names to show which
44    one you meant, as in:
45 SELECT weather.city, weather.temp_lo, weather.temp_hi,
46        weather.prcp, weather.date, cities.location
47     FROM weather JOIN cities ON weather.city = cities.name;
48
49    It is widely considered good style to qualify all column names in a
50    join query, so that the query won't fail if a duplicate column name is
51    later added to one of the tables.
52
53    Join queries of the kind seen thus far can also be written in this
54    form:
55 SELECT *
56     FROM weather, cities
57     WHERE city = name;
58
59    This syntax pre-dates the JOIN/ON syntax, which was introduced in
60    SQL-92. The tables are simply listed in the FROM clause, and the
61    comparison expression is added to the WHERE clause. The results from
62    this older implicit syntax and the newer explicit JOIN/ON syntax are
63    identical. But for a reader of the query, the explicit syntax makes its
64    meaning easier to understand: The join condition is introduced by its
65    own key word whereas previously the condition was mixed into the WHERE
66    clause together with other conditions.
67
68    Now we will figure out how we can get the Hayward records back in. What
69    we want the query to do is to scan the weather table and for each row
70    to find the matching cities row(s). If no matching row is found we want
71    some “empty values” to be substituted for the cities table's columns.
72    This kind of query is called an outer join. (The joins we have seen so
73    far are inner joins.) The command looks like this:
74 SELECT *
75     FROM weather LEFT OUTER JOIN cities ON weather.city = cities.name;
76
77      city      | temp_lo | temp_hi | prcp |    date    |     name      | locatio
78 n
79 ---------------+---------+---------+------+------------+---------------+--------
80 ---
81  Hayward       |      37 |      54 |      | 1994-11-29 |               |
82  San Francisco |      46 |      50 | 0.25 | 1994-11-27 | San Francisco | (-194,5
83 3)
84  San Francisco |      43 |      57 |    0 | 1994-11-29 | San Francisco | (-194,5
85 3)
86 (3 rows)
87
88    This query is called a left outer join because the table mentioned on
89    the left of the join operator will have each of its rows in the output
90    at least once, whereas the table on the right will only have those rows
91    output that match some row of the left table. When outputting a
92    left-table row for which there is no right-table match, empty (null)
93    values are substituted for the right-table columns.
94
95    Exercise:  There are also right outer joins and full outer joins. Try
96    to find out what those do.
97
98    We can also join a table against itself. This is called a self join. As
99    an example, suppose we wish to find all the weather records that are in
100    the temperature range of other weather records. So we need to compare
101    the temp_lo and temp_hi columns of each weather row to the temp_lo and
102    temp_hi columns of all other weather rows. We can do this with the
103    following query:
104 SELECT w1.city, w1.temp_lo AS low, w1.temp_hi AS high,
105        w2.city, w2.temp_lo AS low, w2.temp_hi AS high
106     FROM weather w1 JOIN weather w2
107         ON w1.temp_lo < w2.temp_lo AND w1.temp_hi > w2.temp_hi;
108
109      city      | low | high |     city      | low | high
110 ---------------+-----+------+---------------+-----+------
111  San Francisco |  43 |   57 | San Francisco |  46 |   50
112  Hayward       |  37 |   54 | San Francisco |  46 |   50
113 (2 rows)
114
115    Here we have relabeled the weather table as w1 and w2 to be able to
116    distinguish the left and right side of the join. You can also use these
117    kinds of aliases in other queries to save some typing, e.g.:
118 SELECT *
119     FROM weather w JOIN cities c ON w.city = c.name;
120
121    You will encounter this style of abbreviating quite frequently.
122
123    ^[4] This is only a conceptual model. The join is usually performed in
124    a more efficient manner than actually comparing each possible pair of
125    rows, but this is invisible to the user.