Fix 'too many subqueries' error