Joining two tables
If there is related data in two tables, you often need to query both to get the information you want. You can do this with two queries, but often it is easier and more efficient to query the two tables with a single query. An example of related data is the city and country tables in the world database.
Let's use a simplified version of the city
and country
tables to learn how to join two tables. Here is the city table, consisting of ID
, Name
, and CountryCode
columns:
Here is the country
table, consisting of Code
and Name
columns:
As you can see, the values in the CountryCode
column in the city
table match the values in the Code
column in the country table. Now, let's see what happens if we join the two tables:
- First, write the following query to join both tables:
SELECT * FROM city JOIN country;
This query produces...