Finding Rows in One Table That Match Rows in Another
Problem
You need to write a query that uses information from more than one table.
Solution
Use a join—that is, a query that lists multiple tables in
its
FROM clause and
tells MySQL how to match information from them.
Discussion
The essential idea behind a join is that it combines rows in one table with rows in one or more other tables. Joins enable you to combine information from multiple tables when each table contains only part of the information in which you’re interested. Output rows from a join contain more information than rows from either table by itself.
A complete join that produces all possible row combinations is
called a
Cartesian product. For example,
joining each row in a 100-row table to each row in a 200-row table
produces a result containing 100 ×
200, or 20,000 rows. With larger tables, or joins between more than
two tables, the result set for a Cartesian product can easily become
immense. Because of that, and because you rarely want all the
combinations anyway, a join normally includes an ON or USING clause that specifies how to join rows
between tables. (This requires that each table have one or more
columns of common information that can be used to link them together
logically.) You can also include a WHERE clause that restricts which of the
joined rows to select. Each of these clauses narrows the focus of the
query.
This recipe introduces basic join syntax and demonstrates how joins help you answer specific types ...