How do I know how many rows a Perl DBI query returns?

后端 未结 7 839
遥遥无期
遥遥无期 2020-12-15 18:51

I\'m trying to basically do a search through the database with Perl to tell if there is an item with a certain ID. This search can return no rows, but it can also return one

相关标签:
7条回答
  • 2020-12-15 19:26

    This article may users of MySQL prior to version 8:

    http://www.arraystudio.com/as-workshop/mysql-get-total-number-of-rows-when-using-limit.html

    Luckily since MySQL 4.0.0 you can use SQL_CALC_FOUND_ROWS option in your query which will tell MySQL to count total number of rows disregarding LIMIT clause. You still need to execute a second query in order to retrieve row count, but it’s a simple query and not as complex as your query which retrieved the data.

    Usage is pretty simple. In you main query you need to add SQL_CALC_FOUND_ROWS option just after SELECT and in second query you need to use FOUND_ROWS() function to get total number of rows. Queries would look like this:

    SELECT SQL_CALC_FOUND_ROWS name, email FROM users WHERE name LIKE 'a%' LIMIT 10;

    SELECT FOUND_ROWS();

    The only limitation is that you must call second query immediately after the first one because SQL_CALC_FOUND_ROWS does not save number of rows anywhere.

    Although this solution also requires two queries it’s much more faster, as you execute the main query only once.

    You can read more about SQL_CALC_FOUND_ROWS and FOUND_ROWS() in MySQL docs.

    Sadly, as of 8.0.17:

    The SQL_CALC_FOUND_ROWS query modifier and accompanying FOUND_ROWS() function are deprecated as of MySQL 8.0.17 ...

    Details here.

    0 讨论(0)
提交回复
热议问题