table user:
id,username,group_idtable group:
id,group_nametable log:
id,action,date,user_id表的用途:
user记录用户,group记录用户组,log记录用户日志,现在要做如下统计:
account         group      action次数
user1        group1       100
......现在我sql这么写的:select a.username as account,b.group_name as group,(select count(id) from log where user_id = a.id) as actions from user a left join group b on a.group_id = b.id limit 0,100默认打开页面是没有查询条件的,查出所有记录
用户可查询,根据用户名,group名称,action次数查询
同时可以限定统计action次数的时间范围然后根据给定的统计条件,sql可以是:
select a.username as account,b.group_name as group,(select count(id) from log where user_id = a.id where date > '2008-01-01' and date < '2008-12-31') as actions from user a left join group b on a.group_id = b.id having account like '%account%' and group like '%group%' and actions > 10 and actions <100 limit 0,100这么统计本身没有大的问题,
但是我实际应用中存在这么个问题,应该如何解决?
将数据传给客户端时候,每次取100条,但是我同时需要知道数据库总共有多少条,包括限定查询条件后有多少条,那么象
select a.username as account,b.group_name as group,(select count(id) from log where user_id = a.id where date > '2008-01-01' and date < '2008-12-31') as actions from user a left join group b on a.group_id = b.id having account like '%account%' and group like '%group%' and actions > 10 and actions <100 limit 0,100
这样的sql,如何取取得select count()?

解决方案 »

  1.   

    需要执行两条sql。或者
    在很多分页的程序中都这样写:
    SELECT COUNT(*) from `table` WHERE ......;  查出符合条件的记录总数
    SELECT * FROM `table` WHERE ...... limit M,N; 查询当页要显示的数据
    这样的语句可以改成:
    SELECT SQL_CALC_FOUND_ROWS * FROM `table` WHERE ......  limit M, N;
    SELECT FOUND_ROWS();
    这样只要执行一次较耗时的复杂查询可以同时得到与不带limit同样的记录条数
    第二个 SELECT返回一个数字,指示了在没有LIMIT子句的情况下,第一个SELECT返回了多少行 (若上述的 SELECT语句不包括  SQL_CALC_FOUND_ROWS 选项,则使用LIMIT 和不使用时,FOUND_ROWS() 可能会返回不同的结果)。
      

  2.   

    select SQL_CALC_FOUNDED_ROWS a.username as account,b.group_name as group,(select count(id) from log where user_id = a.id where date > '2008-01-01' and date  < '2008-12-31') as actions from user a left join group b on a.group_id = b.id having account like '%account%' and group like '%group%' and actions > 10 and actions  <100 limit 0,100 ;select FOUND_ROWS();