So I have a MySQL query that is being created dynamically based on parameters passed to my php script. It which is working great, however, I would like to be able to fetch the number of rows it would return before applying the LIMIT statement. It seems to me like this could not be done in one query, but there is so much about MySQL I don’t know that it would not surprise me in the slightest if you could.
I have looked around and found out that COUNT(*) is much faster than mysql_num_rows() but as far as I know, I can’t use either in my case since they would simply be limited by how many results I have specified in my LIMIT, which is usually 30. Also, I would rather not submit a query that doesn’t contain the LIMIT just to get the numbers or rows it would return and then immediately apply the LIMIT and submit the same query.
Here is a sample query:
SELECT DISTINCT w.id, w.resolution, w.views, w.colors, w.favorites
FROM wallpapers AS w
LEFT JOIN (tagmap AS tm, tags AS t)
ON (
w.id = tm.wallpaper_id
AND
tm.tag_id = t.tag_id
) WHERE w.ratio =
(SELECT ratio FROM wallpapers WHERE resolution = '1920 x 1080' LIMIT 1)
AND (
t.tag
IN (
'portal'
)
)
AND (w.verify = 2)
ORDER BY w.id DESC LIMIT 30
I’ve cleaned that up and spent a lot of time optimising it so hopefully it is easy for you to read but also feel free to mention anything else you spot funky in the code that may help speed it up ^^
Back to the question, one way I see to do this would be to stick the conditionals (everything but the SELECT, JOIN, GROUP BY, AND LIMIT basically) from that query onto a SELECT COUNT(*) statement, run that, and then run the actual query to get all the data. Is that the most efficient way or does somebody have a better idea? I would love to hear all possible solutions, thanks! 🙂
I think what you are looking for is CALC_FOUND_ROWS
It’s still two queries though.