VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
mysql -u root -p sakila before you start.
Why the data is split up
Sakila records the language of each film as a number.English once and pointing at it 1,000 times takes less room
than storing it 1,000 times, and correcting a spelling means changing 1 row
rather than 1,000. The cost is that a query wanting the title and the language
name has to read both tables.
How a join works
COLUMN_LIST with the columns you want, LEFT_TABLE with the table you
start from, RIGHT_TABLE with the one you are pulling extra columns out of, and
each COLUMN_NAME with the column on that side that links the 2 tables.
The server takes each row of the left table, finds the rows of the right table
where the ON condition is true, and returns 1 combined row per match.
Examples
1) Read the name instead of the number
AS f and AS l are table aliases, which the next
lesson covers.
What the kinds of join are for
They differ in 1 thing: what happens to a row that finds no match.
An unmatched row kept by an outer join still has to fill the columns it has no
values for, and it fills them with NULL. That is why
IS NULL turns up so often beside a
LEFT JOIN: it is how
you ask for the rows that matched nothing.
CROSS JOIN is the odd one out, because it matches nothing. It is the one you
ask for deliberately when you want every combination, and the one you get by
accident when you leave an ON clause out.
The condition matters more than the keyword
JOIN, INNER JOIN and CROSS JOIN are 1 thing in MySQL, and the grammar
takes an ON clause on any of them or none. So the keyword you type does not
decide your result. The presence of an ON condition does: with one you get
matches, without one you get every combination, whichever of the 3 words you
wrote.
Because the server will not tell them apart for you, write INNER JOIN ... ON
when you mean a match and CROSS JOIN with no ON when you mean every
combination. The keyword is then a note to the next reader rather than an
instruction to the server.
Summary
- Expect information to be split across tables, with 1 table pointing at another by id.
- Use a join to read across those tables in 1 query.
- Read the
ONcondition as the rule for which rows belong together. - Pick the kind of join by what should happen to a row that matches nothing.
- Expect NULL in the columns of a row an outer join kept without a match.
See also
- Table aliases and INNER JOIN — the short names, and the join that keeps only matches
- LEFT JOIN and RIGHT JOIN — the joins that keep unmatched rows
- CROSS JOIN and self join — every combination, and a table joined to itself
- MySQL JOIN performance and common mistakes — what goes wrong once the tables are large

