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.
h开发者_Go百科ow 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
精彩评论