14. Why Tables Join: Keys and Relationships
14.2 One-to-Many: Customers and Shipments (What One Row Means)
Why. Before you join or total anything, you must know what one row stands for. Mistakes about this are the most common reason a report shows the wrong number.
What. The grain of a table is what one row means. In customers, one row is one customer. In shipments, one row is one shipment. One customer can have many shipments, so this is a one-to-many relationship. A customer can also have no shipments at all, like Marina Spices.
How. Count the shipments for each customer id inside the shipments table, without joining anything yet.
Steps
- Write one sentence for each table: one row in customers is one customer.
- Run the example and read the shipment count per customer.
- Notice that customer 206 does not appear, because it has no rows in shipments.
- Keep this in mind: a join with this table will repeat each customer once per shipment.
Examples
Example 1 · dataset: swiftship_logistics
SELECT customer_id,
COUNT(*) AS shipments
FROM shipments
GROUP BY customer_id
ORDER BY customer_id;Output
| customer_id | shipments |
|---|---|
| 201 | 2 |
| 202 | 2 |
| 203 | 2 |
| 204 | 2 |
| 205 | 2 |
Meaning. Each of the customers 201 to 205 has 2 shipments. Customer 206 is missing from this result, because a customer with no shipments has no rows here.
Ravindra Bagale's Tip
Write the grain as a comment at the top of your query, for example: one row = one shipment. It makes wrong totals much easier to spot.
Ravindra Bagale's Tip – मराठी
Query च्या वर grain comment म्हणून लिहा, उदाहरणार्थ: one row = one shipment. मग चुकीचे totals खूप सहज दिसतात.
Ravindra Bagale's Tip – हिंदी
Query के ऊपर grain comment में लिखिए, जैसे: one row = one shipment. इससे गलत totals बहुत आसानी से पकड़ में आते हैं।