Reputation: 2938
I'm trying to write a stored procedure in MySQL. For complicated reasons I have an aggregate query with a bunch of joins to look object ids, and then do another query with more joins (including same tables) to get some data
So, something like this:
CREATE TEMPORARY TABLE ids ENGINE=MEMORY
SELECT MAX(child.id)
FROM parent
JOIN child ON child.parent_id = parent.id
WHERE
GROUP BY child.parent_id;
SELECT *
# MUST SELECT STUFF FROM PARENT, CHILD, AND STUFF JOINED ON CHILD
FROM child
JOIN parent ON parent.id = child.parent_id
# A BUNCH MORE JOINS HERE
WHERE child.id IN (SELECT * FROM ids);
DROP TEMPORARY TABLE IF EXISTS ids;
Now I noticed that first select takes 0.000 seconds. Second select if I replace (SELECT * FROM ids) with a constant list like (1435,2352,43653,34534,...) also takes 0.000 seconds.
However running them both with the temporary table creation takes .6 seconds. 0.o WTH?
So my question is how to skip this temporary table creation, and just pass the list of ids?
Also, if I move the entire first select as a sub-select to the second select then the whole procedure takes way-way longer. More than a minute at which point I give up waiting.
Upvotes: 0
Views: 1687
Reputation: 3191
Try this one:
SELECT *
FROM (
SELECT parent.*, MAX(child.id) as max_id
FROM parent
JOIN child ON child.parent_id = parent.id
WHERE -- some where cond
GROUP BY parent.id
) as parents
JOIN child ON child.id = parents.max_id
-- other joins
and show performance results.
Upvotes: 1