Cursussen/Courses Codesnippets     Top 
SQL select - Join


Join
If you want to use data from more than 1 table in a query you have to perform a "Join". The data from the tables is then merged and included in the result. Every record from one table is merged with every record from the other table (or tables). This can yield a large number of combinations. One speaks here of the "Cartesian product".
Of course you indicate in the query which records are linked to each other. You do this in the "where" clause. You specify the table name followed by a period and the field name (usually the "id" or "primary key") of one table and set it equal to the table name, a period and the field name of the linked field (usually the same "id " but in the other table (="foreign key")).
An example to clarify:
select wine_name, cost
from wine, inventory
where wine.wine_id = inventory.wine_id
and cost < 5.2
In this example, the wines are selected whose cost price is less than 5.2.
The name of the wine is retrieved from the "wine" table. The cost "cost" is taken from the "inventory" table.
The link between both tables is the "wine_id" present in both tables.
If you also want to know from which vineyard those wines come, add the table "winery" to the query and indicate the correct link.
select winery_name, wine_name, cost
from winery, wine, inventory
where winery.winery_id = wine.winery_id
and wine.wine_id = inventory.wine_id
and cost < 5.2
The field "winery_id" appears in the table "winery" (="primary key") and in the table "wine" (="foreign key").
If the same field name is used in different tables and you would include that field name in the query after the word "select" then you should put the table name and a period before the field name so that it is clear which data to show.


X

Paragraphs

Join