Sub topic 6
Joining Three or More Tables
This chapter assumes you know basic SELECT, WHERE, and ORDER BY syntax, primary and foreign keys, and a two-table INNER JOIN. A multi-table join applies the same idea repeatedly: each join adds rows that match the new table.
Suppose these tables describe a store:
customershas one row per customer.ordershas one row per order andcustomer_idlinks tocustomers.id.order_itemshas one row per product in an order.productshas one row per product andproduct_idlinks toproducts.id.
Follow the relationships
To find the products in each customer's order, join the tables along their foreign-key relationships:
SELECT
c.name AS customer,
o.id AS order_id,
p.name AS product,
i.quantity
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id
INNER JOIN order_items AS i
ON i.order_id = o.id
INNER JOIN products AS p
ON p.id = i.product_id
ORDER BY c.name, o.id, p.name;The query starts with customers. The first join keeps customers that have matching orders. The second join keeps those orders that have matching order items. The final join adds the product information for each item.
Every INNER JOIN needs its own ON condition. Each condition should connect the new table to a table already in the query.
Use aliases and qualify columns
An alias is a short name assigned with AS. Aliases make long queries easier to read:
FROM customers AS cA qualified column name includes its table alias, such as c.name or o.id. Qualification prevents ambiguity when several tables have columns with the same name. For example, both orders and products might have an id column, so writing only id may cause an error or make the query unclear.
The order of inner joins usually does not change the matching rows, but clear relationship order helps you check the query. Add one table at a time and verify that its ON condition uses the correct key.
| Join | Relationship | Information added |
|---|---|---|
| `customers` to `orders` | One customer to many orders | Customer and order data |
| `orders` to `order_items` | One order to many items | Quantity per item |
| `order_items` to `products` | Each item to one product | Product name |
Watch the number of rows
A customer with two orders and three items in each order can produce six result rows. The customer name repeats because the result contains one row per matching item, not one row per customer.
When you need one summary row per customer, group the joined result:
SELECT
c.name AS customer,
COUNT(DISTINCT o.id) AS order_count,
SUM(i.quantity) AS item_count
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id
INNER JOIN order_items AS i
ON i.order_id = o.id
GROUP BY c.id, c.name
ORDER BY c.name;Grouping by both c.id and c.name identifies each customer while remaining safe if two customers share the same name.
Exercise
Which join condition should connect order_items to products?
Show answer
Use ON p.id = i.productid, because each order item stores the product's key in productid.