I have the following table called "table3"
+------+
| name |
+------+
| aaa |
| aaa |
| aaa |
| aaa |
| aaa |
| aaa |
| bbb |
| bbb |
| bbb |
| bbb |
| ccc |
| ccc |
| ccc |
| ccc |
| ccc |
| ccc |
| ccc |
| ccc |
| ccc |
+------+
when I got count for each name, I got
mysql>select name,count(name) as count from table3 group by name order by name;
+------+-------+
| name | count |
+------+-------+
| aaa | 6 |
| bbb | 4 |
| ccc | 9 |
+------+-------+
so I ran the following query to return and names and max count net to them
mysql> select name from (select name,count(name) as count from table3 group by name order by name) as tbl where tbl.count=(select max(count) from tbl);
expecting the following result
+------+
| name |
+------+
| ccc |
+------+
but I get this error
ERROR 1146 (42S02): Table 'tests.tbl' doesn't exist
Ihave done aliasing correctly, but the table alias "tbl" isn't identified in the part ".....unt=(select max(count) from tbl)"
then I used this queries too
mysql> select name from (select name,count(name) as count from table3 group by name order by name) as tbl where tbl.count=(select max(count) from tbl) as tb1;
mysql> select name from (select name,count(name) as count from table3 group by name order by name) as tbl where tbl.count=((select max(count) from tbl) as tb1); //extra couple of parenthesis
they also give some different errors. Nothing was succeeded
How to fix this problem without deriving another table from the original table (table3)
You can use limit
:
select name
from t
group by name
order by count(*) desc
limit 1;
If there can be ties and you want all values in that case, then use rank()
:
select name
from (select name, count(*) as cnt,
rank() over (order by count(*) desc) as seqnum
from t
group by name
) n
where seqnum = 1;