简体   繁体   English

按结果分组的MySql数

[英]MySql count of group by result

I'm trying to get records based on applied search criteria. 我正在尝试根据应用的搜索条件获取记录。 At a time I'm only selecting 50 rows(for pagination of the table used on webpage). 我只选择了50行(用于网页上使用的表的分页)。 But I also need the total number of rows that satisfies the search criteria (to show 1-50 out of <total> records & so on). 但我还需要满足搜索条件的total数(显示1-50 out of <total> records等等)。

Following query gives me records group by userid. 以下查询按用户ID给出了记录组。

select * from user 
group by userid
where name like '%hhh%' 
limit 50 offset 0

Here I'll will get first 50 records that satisfies the criteria, but total search results can be greater than 50. I need this total count along with other query result. 在这里,我将获得满足条件的前50条记录,但总搜索结果可能大于50.我需要此总计数以及其他查询结果。

I'd use a separate query: 我会使用单独的查询:

select count(*) from user
group by userid
where name like '%hhh%'

Your query will be much quicker and can be run each time another 50 rows are selected, then you can run this longer running query once, to get the total 您的查询会更快,并且每次选择另外50行时都可以运行,然后您可以运行此更长时间运行的查询一次,以获得总计

try this query.. 试试这个查询..

select count(*) as total,userid from users
where name like '%hhh%' 
 group by userid limit 50 offset 0

MySQL supports this with the SQL_CALC_FOUND_ROWS option. MySQL使用SQL_CALC_FOUND_ROWS选项支持此功能 Something like the following: (adapted (but untested!) from the docs): 类似于以下内容:(从文档中修改(但未经测试!):

mysql> SELECT SQL_CALC_FOUND_ROWS * FROM user
-> WHERE name like '%hhh%' LIMIT 50;
mysql> SELECT FOUND_ROWS();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM