Let's say I have this query:
(SELECT pets.id, "pets" AS "table" FROM pets WHERE name="Joey")
UNION ALL
(SELECT toys.id, "toys" AS "table" FROM (SELECT id, "pets" AS "table" FROM pets WHERE name="Joey") AS parentQuery, toys WHERE type="Ball" AND pet_id=parentQuery.id)
UNION ALL
(SELECT owners.id, "owners" AS "table" FROM (SELECT id, "pets" AS "table" FROM pets WHERE name="Joey") AS parentQuery, owners WHERE name="Issac" AND pet_id=parentQuery.id)
SQL Fiddle: http://sqlfiddle.com/#!9/1637a/1
The idea here is to get the ID columns for related rows in multiple one-to-many scenarios. A couple of questions:
- While I'm hopeful that MySQL optimizes to some extent with query caching the results for having the same initial query here embedded into the other
UNION
'ed queries as a sub-query, is it possible to safely and cleanly use SQL variables (or something) to reference the results from the first query in the other queries... in order to avoid repeating the query and any bundled parameters again for each additionalUNION
'ed query? - (optional) If you think this is bad/reckless SQL design, please let me know. I'm sure this could be done with
JOIN
variants, but I'm just not sure if the performance would be better with a lot of joins than just splitting it up like this? I've heard differing opinions.
Thanks! I've seen this response already and think that something similar could work, but I've generally avoided SQL variables thus far, so I'm not sure how to structure it with UNION
'ed queries: How to optimize huge query with repeated subqueries