如何在MYSQL中的单个查询中计算和限制记录?

2021-12-30 00:00:00 count php mysql

我正在按如下方式搜索表中的记录:

SELECT Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;

现在,我添加了 LIMIT 来维护我的分页.但是当用户搜索单词prashant"时,我拥有的prashant"总记录数为 124.但是由于应用于查询的限制,所以它只在我的 PHP 脚本中获取 10 条记录,当我计算 PHP 代码中的 mysql 变量时,它返回找到的总记录数为 10.

所以基本上我想使用单个查询进行计数和限制,通过对上述查询进行一些修改,我想要记录的总数(124).我不想运行单独的 count(*) 查询来计算查询找到的总结果.

谢谢.

解决方案

SELECT SQL_CALC_FOUND_ROWS身份证、姓名从 my_table在哪里名称 LIKE '%prashant%'限制 0, 10;# 查找总行数选择 FOUND_ROWS();

更多信息

I am searching for records in a table as follows:

SELECT Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;

Now, I am adding LIMIT to maintain my paging. But when user searches for word 'prashant' then total records I have is 124 for 'prashant'. But as the limit applied to the query so it only fetches 10 records in my PHP script and when I am count the mysql variable in PHP code it returns total records found is 10.

So basically I want to count and Limit using a single query, by making some modification in the above query, I want the total count (124) of records. I don't want to run a separate count(*) query for just counting the total result found by the query.

Thanks.

解决方案

SELECT SQL_CALC_FOUND_ROWS
  Id, Name
FROM my_table
WHERE
  Name LIKE '%prashant%'
LIMIT 0, 10;

# Find total rows
SELECT FOUND_ROWS();

more info

相关文章