Underlying data:
mysql> select * from parent;
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
| 1 | Joe | Wilkenson |
| 2 | Bob | Thompson |
| 3 | Bob | Ericson |
+----+------------+-----------+
mysql> select * from child;
+----+-----------+------------+-----------+---------+
| id | parent_id | first_name | last_name | fingers |
+----+-----------+------------+-----------+---------+
| 1 | 1 | Carla | Wilkenson | 10 |
| 2 | 1 | Peter | Wilkenson | 8 |
| 3 | 2 | Sam | Thompson | 10 |
| 4 | 3 | Beth | Ericson | 10 |
| 5 | 3 | Georgie | Ericson | 10 |
| 6 | 3 | Kyle | Ericson | 7 |
+----+-----------+------------+-----------+---------+
Goal: Figure out the total number of children's fingers, grouped by the parent's first name.
SELECT
parent.first_name,
( SELECT SUM(fingers) FROM child WHERE child.parent_id IN ([collapsed parent.ids]) ) AS `kid_fingers`
FROM parent
GROUP BY parent.first_name;
I know that, with this specific example, the goal can be achieved by simply moving the subquery into a JOIN
with a SUM(child.fingers)
. My actual scenario is far more complicated with a lot more table joins that would result in SUM()
returning a very inflated and inaccurate number due to row duplication.
I also attempted to JOIN
against a subquery but that's resulting in an unavoidable full scan on a large table which isn't feasible in my environment.
That leaves a SELECT
subquery but there's the obvious problem that the field I need to compare against gets collapsed by the GROUP BY
. This seems like a really good opportunity for MySQL to offer an aggregate function that simply brings up collapsed values for comparison, but I don't think one exists?
Any other tricks that might work for this? Worst case scenario I can do a REGEXP
compare against GROUP_CONCAT()
but that seems gross (and potentially risky) for many reasons. I'm unfortunately dealing with a very large and dynamically-built query that can have a lot of different GROUP BY
combinations, so a full refactor or redesign is problematic.
P.S. Don't ask why the children are missing fingers. I just needed something to count.