Found and fixed this bug in the PHP version:
This query
SELECT * FROM (SELECT * FROM `foo` UNION ALL SELECT * FROM `bar`) AS `baz`
is treated as
SELECT * FROM (SELECT * FROM `foo`) AS `baz`
Here's the commit with the fix in the PHP version, you should be able to port it relatively straightforwardly if you run into the same issue.