Getting the number of rows with a GROUP BY query

后端 未结 5 1158

I have a query to the effect of

SELECT t3.id, a,bunch,of,other,stuff FROM t1, t2, t3 
WHERE (associate t1,t2, and t3 with each other) 
GROUP BY t3.id 
LIMIT          


        
相关标签:
5条回答
  • 2020-12-12 16:31

    All ans given will execute the query and then find the count. Distinct is definitely slower than group by on large dataset.

    Best way to find the count of group by is below

    SELECT 
        sum(1) as counttotal
    FROM (
        Your query with group by operator
    ) as T
    

    This will find the count while calculating group by.

    0 讨论(0)
  • 2020-12-12 16:40

    Are the "bunch of other stuff" all aggregates? I'm assuming so since your GROUP BY only has t3.id. If that's the case then this should work:

    SELECT
         COUNT(DISTINCT t3.id)
    FROM...
    

    The other option of course is:

    SELECT
         COUNT(*)
    FROM
         (
         <Your query here>
         ) AS SQ
    

    I don't use MySQL, so I don't know if these queries will work there or not.

    0 讨论(0)
  • 2020-12-12 16:44

    There is a nice solution in MySQL.

    Add the keyword SQL_CALC_FOUND_ROWS right after the keyword SELECT :

    SELECT SQL_CALC_FOUND_ROWS t3.id, a,bunch,of,other,stuff FROM t1, t2, t3 
    WHERE (associate t1,t2, and t3 with each other) 
    GROUP BY t3.id 
    LIMIT 10,20
    

    After that, run another query with the function FOUND_ROWS() :

    SELECT FOUND_ROWS();
    

    It should return the number of rows without the LIMIT clause.

    Checkout this page for more information : http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows

    0 讨论(0)
  • 2020-12-12 16:49

    Using sub queries :

    SELECT COUNT(*) FROM    
    (
    SELECT t3.id, a,bunch,of,other,stuff FROM t1, t2, t3 
    WHERE (associate t1,t2, and t3 with each other) 
    GROUP BY t3.id 
    )    
    as temp;
    

    so temp contains the count of rows.

    0 讨论(0)
  • 2020-12-12 16:50

    You're using MySQL, so you can use their function to do exactly this.

    SELECT SQL_CALC_FOUND_ROWS t3.id, a,bunch,of,other,stuff 
    FROM t1, t2, t3 
    WHERE (associate t1,t2, and t3 with each other) 
    GROUP BY t3.id 
    LIMIT 10,20;
    
    SELECT FOUND_ROWS(); -- for most recent query
    

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

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