Bring the records together.
Combine related tables and calculate one useful result per group.
01 The idea
A join combines rows according to a relationship. An inner join retains matches; a left join retains every row on the left, adding NULL values when no right-side match exists. GROUP BY gathers rows for aggregate calculations. Join cardinality matters: an accidental many-to-many multiplication can inflate totals even when the SQL is syntactically valid.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from lab_support import mysql_lab
with mysql_lab() as (connection, cursor):
cursor.execute("""SELECT p.name, SUM(t.minutes) AS minutes
FROM lab_projects AS p
JOIN lab_tasks AS t ON t.project_id = p.id
WHERE t.done = %s
GROUP BY p.id, p.name
ORDER BY p.id""", (False,))
for row in cursor.fetchall():
print(row["name"], int(row["minutes"]))Orbit 60 Atlas 30
03 Under the hood
- 1
The ON condition expresses the project relationship. A missing join predicate would create combinations rather than related records.
- 2
The WHERE filter removes completed tasks before aggregation, then SUM calculates the remaining effort per project.
- 3
To retain projects with no unfinished tasks, use a LEFT JOIN and put the unfinished-task condition in the ON clause, with COALESCE around the aggregate. Putting that right-table filter in WHERE can eliminate the unmatched rows.
04 Your turn, builder
Count all tasks per project, retaining projects that might have no tasks.
Reveal one possible solution +
from lab_support import mysql_lab
with mysql_lab() as (connection, cursor):
cursor.execute("SELECT p.name, COUNT(t.id) AS total FROM lab_projects p LEFT JOIN lab_tasks t ON t.project_id = p.id GROUP BY p.id, p.name ORDER BY p.id")
for row in cursor.fetchall():
print(row["name"], row["total"])05 Check your signal
What does a LEFT JOIN preserve?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.