I have the following query that when executed, it just runs for hours and eventually the server times out.
SELECT l.mloc_id, COUNT( l.tabc_id ) , l.tabc_id, e.establishment_id, e.name, l.LocationName, l.naics, l.cuisine, l.cuisine2, l.service, l.www, l.owner, l.email, l.status
FROM vg_ydrink2.m_loc AS l
JOIN vg_ydk.permit_beverage AS pb ON ( l.tabc_id = pb.permit_code
AND pb.create_date = (
SELECT MAX( create_date )
FROM vg_ydk.permit_beverage
WHERE permit_code = l.tabc_id ) )
JOIN vg_ydk.establishment AS e ON ( pb.establishment_id = e.establishment_id )
GROUP BY l.mloc_id
ORDER BY `l`.`tabc_id` ASC
LIMIT 1 , 30
No errors are reported. It simply never gets completed.
The problem lies in the sub-select, because when removing it, the query executes without a problem. I also don’t think it’s the group function causing the issue, because I have tried keeping the subquery but removing the MAX and that did not work either.
Any thoughts?
Thank you in advance.
***EDIT: After having played with the create_date index a bit, I realized that due to the nature of its values, its cardinality is constantly very low. For that reason, it is not treated as an index by the query and as a result, too many rows are constantly loaded.
I have since changed the query altogether, so this is not an issue anymore. If anybody comes across a similar issue, make sure the used field is indexed properly. Analyze/optimize/repair your table if need be.
M.
Try this variation: