I am doing a query that converts rows to columns similar to this post but have encountered a performance problem. Here is the query:-
SELECT
Info.Customer,
Answers.Answer,
Answers.AnswerDescription,
Details.Code1,
Details.Code2,
Details.Code3
FROM
Info
LEFT OUTER JOIN Answers
ON Info.AnswerID = Answers.AnswerID
LEFT OUTER JOIN
(SELECT
ReferenceNo,
MAX(CASE DetailsIndicator WHEN 'cde1' THEN DetailsCode ELSE NULL END ) Code1,
MAX(CASE DetailsIndicator WHEN 'cde2' THEN DetailsCode ELSE NULL END ) Code2,
MAX(CASE DetailsIndicator WHEN 'cde3' THEN DetailsCode ELSE NULL END ) Code3
FROM DetailsData
GROUP BY ReferenceNo) Details
ON Info.ReferenceNo = Details.ReferenceNo
WHERE Info.Date BETWEEN x AND y
There are less than 300 rows returned, but the Details table is about 180 thousand rows.
The query takes 45 seconds to run in half the time.
Note the inner query takes 7 seconds to run.
When I type show processlist; into MYSQL it is hanging on “Sending Data”.
Any thoughts as to what the performance problem might be?
First, the inner subselect that queries the “Details” result is querying against ALL entries… is that what you want? I don’t think so. You only appear to want results based on a reference number that qualifies from the outer date check.
So, I would change your inner select to include…
This way, you are only getting details associated with reference numbers within the date range in question.