I'm trying to sort a table (let's call it Parent) by the number of relations it has to two tables let's call them Child1 and Child2). Right now I'm doing it like this:
SELECT Master.id
(SELECT COUNT(*) FROM Child1 WHERE Child1.id=Master.id)
+ (SELECT COUNT(*) FROM Child2 WHERE Child2.id=Master.id) AS score
ORDER BY score DESC;
It works as expected, but is difficult to maintain as I have no way of knowing what the intermediate values of the subqueries are. What I'd like to is the following:
SELECT Master.id
(SELECT COUNT(*) FROM Child1 WHERE Child1.id=Master.id) AS child1_score,
(SELECT COUNT(*) FROM Child2 WHERE Child2.id=Master.id) AS child2_score,
child1_score + child2_score AS score
ORDER BY score DESC;
But that gives me an error saying child1_score and child2_score aren't defined. The only clean way I can think of doing this is with an additional level of nested subqueries:
SELECT child1_score + child2_score AS score, id FROM
(SELECT Master.id
(SELECT COUNT(*) FROM Child1 WHERE Child1.id=Master.id) AS child1_score,
(SELECT COUNT(*) FROM Child2 WHERE Child2.id=Master.id) AS child2_score)
ORDER BY score DESC;
But that seems like it would be far worse for memory.
Is there a better way to deal with this that I'm not seeing? I'm using MySQL but I'd like to stick to standard syntax if possible.