MySQL - How to count rows before pagination?

痞子三分冷 提交于 2019-12-05 08:56:15

Modify the query like this:

SELECT SQL_CALC_FOUND_ROWS * FROM accounts ... LIMIT ...

This will return the same limited/offset result as before (the first page of results, for example), but if you then immediately send this second query to the server...

SELECT FOUND_ROWS();

The server will return a count of the total number of rows that would have been returned if the LIMIT had not been imposed on the previous query. There's your total number of results.

This will, of course, mean that your initial query takes longer, because the optimizer can't take any shortcuts that might allow it to stop evaluating rows once the LIMIT is satisfied, but in some cases, no such shortcuts are available anyway.

This is the "official" mechanism for doing what you are trying to accomplish.

http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_found-rows

Rafael Marins

You could use do something like this:

SELECT (select count(*) from produtos) as counter, column1, column2, column3, column4 FROM accounts AS A INNER JOIN profiles AS P ON A.account_id = P.account_id WHERE A.username LIKE ? OR P.name LIKE ? OR P.name LIKE ? OR P.surname LIKE ? OR P.surname LIKE ? LIMIT ?,?;

Instead of selecting all (*), you use each column name, and create another column called counter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!