Search code examples
phpmysqlsqlsql-calc-found-rows

Wrong result with FOUND_ROWS() in mySQL


I have a total of 6 rows. When I do a query (say SELECT * from table) and I have

  • LIMIT 3 => FOUND_ROWS() gives 3 => 3 rows is retrieved
  • LIMIT 1, 3 => FOUND_ROWS() gives 4 => 3 rows is retrieved
  • LIMIT 2, 3 => FOUND_ROWS() gives 5 => 3 rows is retrieved
  • LIMIT 3, 3 => FOUND_ROWS() gives 6 => 3 rows is retrieved
  • LIMIT 4, 3 => FOUND_ROWS() gives 6 => 2 rows is retrieved

Any idea what is the cause of this weird behavior?

SQL QUERY

SELECT `places`.*, `category`.*, COUNT(places_reviews.place_id) AS num_reviews, (places_popularity.rating_1 + 2*places_popularity.rating_2 + 3*places_popularity.rating_3 + 4*places_popularity.rating_4 + 5*places_popularity.rating_5)/(places_popularity.rating_1 + places_popularity.rating_2 + places_popularity.rating_3 + places_popularity.rating_4 + places_popularity.rating_5) AS average_rating, FOUND_ROWS() AS num_rows FROM (`places`) JOIN `category` ON `places`.`category_id` = `category`.`category_id` LEFT JOIN `places_reviews` ON `places_reviews`.`place_id` = `places`.`id` LEFT JOIN `places_popularity` ON `places_popularity`.`place_id` = `places`.`id` WHERE `places`.`category_id` = 1 AND `places`.`name` LIKE '%%' GROUP BY `places`.`id` ORDER BY `id` desc LIMIT 3

Or in a block:

SELECT `places`.*, `category`.*, 
COUNT(places_reviews.place_id) AS num_reviews, 
(places_popularity.rating_1 + 2*places_popularity.rating_2 + 3*places_popularity.rating_3 + 4*places_popularity.rating_4 + 5*places_popularity.rating_5)/(places_popularity.rating_1 + places_popularity.rating_2 + places_popularity.rating_3 + places_popularity.rating_4 + places_popularity.rating_5) AS average_rating, FOUND_ROWS() AS num_rows FROM (`places`) 
JOIN `category` ON `places`.`category_id` = `category`.`category_id` 
LEFT JOIN `places_reviews` ON `places_reviews`.`place_id` = `places`.`id` 
LEFT JOIN `places_popularity` ON `places_popularity`.`place_id` = `places`.`id` 
WHERE `places`.`category_id` = 1 
    AND `places`.`name` LIKE '%%' 
GROUP BY `places`.`id` 
ORDER BY `id` desc LIMIT 3

Solution

  • Edit :

    This is what you are looking for : http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows

    So in your query :

    SELECT sql_calc_found_rows .....