Sub topic 9
One-to-Many Matches and Row Counts
This chapter assumes you know SELECT, FROM, WHERE, and ORDER BY, plus the difference between a primary key and a foreign key. The examples use the orders and order_items tables from the sample schema.
A one-to-many relationship means that one row in one table can match several rows in another table. For example, one order can contain several order items. An inner join returns one result row for each matching pair, so the order's values repeat.
SELECT
o.id AS order_id,
o.total,
i.product_id,
i.quantity
FROM orders AS o
INNER JOIN order_items AS i
ON i.order_id = o.id
ORDER BY o.id, i.product_id;If order 101 has three items, this query returns three rows for order 101. The value o.total appears in all three rows. The join does not copy the order physically. It repeats the order columns in the result so that each matching item can be shown.
| Relationship | Matching child rows | Result rows for that parent |
|---|---|---|
| One order to many items | 3 | 3 |
A join can multiply rows again when it crosses another one-to-many relationship. Suppose each order item points to a product, and each product has several reviews. Joining orders, items, products, and reviews can produce one row for every item-review combination. This is useful when you need those combinations, but it can surprise you when counting or summing.
For example, this query counts items, not orders:
SELECT
o.id AS order_id,
COUNT(*) AS item_count
FROM orders AS o
INNER JOIN order_items AS i
ON i.order_id = o.id
GROUP BY o.id
ORDER BY o.id;COUNT(*) counts the joined rows. If an order has four items, its count is four. To count distinct orders across a joined result, use COUNT(DISTINCT ...):
SELECT COUNT(DISTINCT o.id) AS orders_with_items
FROM orders AS o
INNER JOIN order_items AS i
ON i.order_id = o.id;A common error is summing a parent value after joining it to children:
-- Wrong when an order has multiple items.
SELECT SUM(o.total) AS inflated_revenue
FROM orders AS o
INNER JOIN order_items AS i
ON i.order_id = o.id;Each order total appears once per item, so the sum is inflated. Aggregate orders before joining to item-level data, or select one row per order in a separate query. The correct solution depends on whether the intended measure is order revenue, item revenue, or a count of items.
Exercise
An order has five matching rows in order_items. How many rows does an inner join return for that order, and what does COUNT(*) count after grouping by order ID?
Show answer
It returns five rows, and COUNT(*) returns five because it counts the five joined item rows.