Search code examples
phpmysqlsql-calc-found-rows

Mysql FOUND_ROWS with HAVING statement


EDIT: As it turns out, it appears that the code IS running as intended. It was just a debugging issue. Sorry to disturb!

I'm running a large query that involves several filters and JOINs, and also I'm paginating the results therefore the query was running twice.

I tried using SQL_CALC_FOUND_ROWS to avoid running the query twice, but since I'm filtering with HAVING statements I'm getting the unfiltered total, before the "having statement". I need to run the HAVING since the original query relies on counting stuff - which I know is awful but I don't have the permissions to modify the DB structure right now.

An idea of my SQL:

SELECT SQL_CALC_FOUND_ROWS u.id as user_id,
               u.full_name as full_name,
               u.email as email,
               COUNT(stuff) as logs,
    FROM
        user u
        LEFT JOIN
        profile u_p on u_p.user_id = u.id 
        GROUP BY u.id 
        HAVING logs>5
    LIMIT 15

when I run the new SQL query SELECT FOUND_ROWS() as total_rows I get the full amount of u.id ROWS and not the filtered one. (This only happens with a HAVING statement, and not a WHERE clause)


Solution

  • As it turns out, it appears that the code IS running as intended. It was just a debugging issue. Sorry to disturb!