I am running two queries to my database for pagination reasons. As such, each query is nearly identical. My COUNT(*) query is not returning the number of results that the non-count query is. I’m baffled as to why this is the case. The queries are below.
SELECT p.host_id, p.rating_support, p.rating_tech, MAX(p.rating_overall) AS rating_overall, p.publish_rating, h.name, prices.price, prices.term_duration
FROM plans p
INNER JOIN hosts AS h ON h.id = p.host_id
INNER JOIN (SELECT plan_id, price, term_duration FROM prices WHERE price > 0 AND price < 50 AND term_duration = 1) prices ON prices.plan_id = p.id
WHERE p.published = 1 AND h.published = 1
GROUP BY p.host_id
ORDER BY rating_overall desc LIMIT 0, 12
SELECT COUNT(*) AS count
FROM plans p
INNER JOIN hosts AS h ON h.id = p.host_id
INNER JOIN (SELECT plan_id, price, term_duration FROM prices WHERE price > 0 AND price < 50 AND term_duration = 1) prices ON prices.plan_id = p.id
WHERE p.published = 1 AND h.published = 1
GROUP BY p.host_id
I’m not an expert at MySQL. Besides the count not providing the correct number of results, the non-count query works perfectly.
Any light on this problem would be great.
With the help of Dems’ comment (hunt down and upvote him somewhere :), I created this query. Notice that I removed the subquery, because it seemed unnecessary:
My original answer:
To get the number of total row, you have to wrap the
GROUP BYquery into an outerSELECT:Or you could use
SQL_CALC_FOUND_ROWS+FOUND_ROWS()http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows
First, simply select the required rows, but add
SQL_CALC_FOUND_ROWS:Second, get the number of rows that would have been returned if there weren’t a
LIMITstatement in the first query:Update:
SQL_CALC_FOUND_ROWS+FOUND_ROWS()doesn’t seem very reliable, always returs zero for unknown reason (not just me: FOUND_ROWS() keeps returning 0 ):http://sqlfiddle.com/#!2/7304d/8