简体   繁体   中英

mysql group by and count rows problem

let's say mysql is something like this

select x,y 
from xx 
group by y

i want to know how many rows that select will get, i tried to use count but it will n't return all results since i'm using group by.

how to do that?

Thanks

You can wrap your query like so:

SELECT COUNT(*) FROM
  (select x,y  
    from xx  
    group by y) sub;

Suppose you have a table with the content below:

 -------------------
| ID | NAME | GROUP |
+-------------------+
| 1  |  A   |  1    |
+-------------------+
| 2  |  B   |  2    |
+-------------------+
| 3  |  C   |  2    |
+-------------------+
| 4  |  D   |  3    |
+-------------------+
| 5  |  E   |  1    |
+-------------------+
| 6  |  F   |  3    |
+-------------------+

The following self LEFT JOIN counts the number of distinct values in GROUP.

SELECT COUNT(*)
FROM table AS t1
LEFT JOIN table AS t2 ON t2.GROUP = t1.GROUP AND t2.ID > t1.ID
WHERE t2.id IS NULL;

What this query does is find out, for each group, the element with the highest id.

You can check my ans https://stackoverflow.com/a/36449637/2439715

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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