Add Indexes: These may help:
b: INDEX(uid, name, email)
doc: INDEX(order_id, document_file)
Remove LEFT: Is there a reason for LEFT JOIN
instead of JOIN
? I think not. See if you get the same results without LEFTs
.
Remove bogus test: Why WHERE es.id
? If id
is the PRIMARY KEY
of es
, that test will always be true.
Improve GROUP+ORDER: Change
GROUP BY es.id
ORDER BY es.joindate DESC
LIMIT 0,25
-->
GROUP BY es.joindate, es.id
ORDER BY es.joindate DESC, es.id DESC
LIMIT 0,25
That avoids two passes over the data -- one for the GROUPing, and another for the ORDERing. Meanwhile, I assume that my grouping and ordering is "just as good".
Turn inside-out: That brings up another issue, one I call "explode-implode". That's where you Join together a lot of rows, only to get rid of most of them. So...
Start by finding the 25 ids desired with as little effort as possible:
SELECT id
FROM usersubinfo
WHERE is_active = 'Yes'
GROUP BY joindate, id
ORDER BY joindate DESC, id DESC
LIMIT 0,25
And include that as a 'derived' table in the rest:
SELECT es.*, c.mainsubarea AS subject,
b.name, b.email,
GROUP_CONCAT(doc.document_file SEPARATOR "|") document_file
FROM ( put the above Select here
) AS ids
JOIN usersubinfo AS es USING(id)
JOIN userinfo b ON (es.uid=b.uid)
JOIN lkptsubjectarea c ON (es.mainsubjectarea=c.id)
JOIN lkptdeliverytime d ON (es.deliverytime = d.id)
JOIN documents doc ON (es.id = doc.order_id)
ORDER BY joindate DESC, id DESC; -- yes, repeat this
This is likely to be faster because the tables other than usersubinfo
will be touched only 25 times.
(I think this will happen to avoid the "only_full_group_by" issue to which Parfait refers.)