Run a query with a LIMIT/OFFSET and also get the total number of rows

后端 未结 4 2086
醉话见心
醉话见心 2020-12-12 11:31

For pagination purposes, I need a run a query with the LIMIT and OFFSET clauses. But I also need a count of the number of rows that would be return

4条回答
  •  失恋的感觉
    2020-12-12 11:55

    Its bad practice to call two times same query for Just to get the total number of rows of the returend result. It will take execution time and will waste the server resource.

    Better, you can use SQL_CALC_FOUND_ROWS in the query which will tell the MySQL to fetch the total number of row count along with the limit query results.

    Example set as:

    SELECT SQL_CALC_FOUND_ROWS employeeName, phoneNumber FROM employee WHERE employeeName LIKE 'a%' LIMIT 10;
    
    SELECT FOUND_ROWS();
    

    In the above Query, Just add SQL_CALC_FOUND_ROWS option in the rest required query and execute the second line i.e. SELECT FOUND_ROWS() returns the number of rows in the result set returned by that statement.

提交回复
热议问题