• Learning MySQL By Example
  • Introduction
  • 1. How to Retrieve Data From a Single Table
  • 2. How to Retrieve Data from Multiple Tables
  • 3. Using Functions
  • 4. How to Insert, Update, Delete Data in Tables
  • 5. Summary Queries and Aggregate Functions
  • 6. Working With Subqueries
  • 7. SQL Views
  • 8. SQL Indexes
  • Glossary
  • Index
  • Download
  • Translations
  • 2.1

    The JOIN Clause

    The Join Clause

    • A JOIN clause allows you to access data from two or more tables in a query.
    • A join links to tables on a common key between the two tables. Usually the primary key on one table is compared to the foreign key on another table using the equals ( = ) sign. This is an equijoin or an inner-join. However, other comparison operators are also valid.
    • If column names from each table in the join have the same name, they must be qualified with the table name or a table alias.

    Below is a basic example of a SQL statement with an inner join clause using explicit syntax.

    1    USE world;
    2    SELECT city.name AS "City Name", 
    3        country.name AS "Country Name" 
    4    FROM country 
    6        JOIN city 
    5            ON city.CountryCode = country. Code;

    You could write SQL statements more succinctly with an inner join clause using table aliases. Instead of writing out the whole table name to qualify a column, you can use a table alias.

    1    USE world;
    2    SELECT ci.name AS "City Name", 
    3        co.name AS "Country Name" 
    4    FROM city ci 
    5        JOIN country co 
    6            ON ci.CountryCode = co.Code;

    The results of the join query would yield the same results as shown below whether or not table names are completely written out or are represented with table aliases. The table aliases of co for country and ci for city are defined in the FROM clause and referenced in the SELECT and ON clause:

    Results:

    01_joins.png

    Let us break the statement line by line:

    USE world;

    SELECT ci.name AS “City Name”, co.name AS “Country Name”

    FROM city ci

    JOIN country co

    ON ci.CountryCode = co.Code;

    This content is provided to you freely by EdTech Books.

    Access it online or download it at https://edtechbooks.org/learning_mysql/the_join_clause.