MySQL 中 GROUP BY 返回的行数是多少?
mysqlmysqli database
您可以使用 GROUP_CONCAT() 来实现这一点。为了理解上述概念,让我们创建一个表。
创建表的查询如下
mysql> create table groupByDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(100) -> ); Query OK, 0 rows affected (1.31 sec)
使用 insert 命令在表中插入一些记录。
查询如下
mysql> insert into groupByDemo(Name) values('John'); Query OK, 1 row affected (0.19 sec) mysql> insert into groupByDemo(Name) values('Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into groupByDemo(Name) values('Carol'); Query OK, 1 row affected (0.10 sec) mysql> insert into groupByDemo(Name) values('Bob'); Query OK, 1 row affected (0.24 sec) mysql> insert into groupByDemo(Name) values('Bob'); Query OK, 1 row affected (0.23 sec) mysql> insert into groupByDemo(Name) values('Bob'); Query OK, 1 row affected (0.17 sec) mysql> insert into groupByDemo(Name) values('John'); Query OK, 1 row affected (0.16 sec) mysql> insert into groupByDemo(Name) values('John'); Query OK, 1 row affected (0.07 sec) mysql> insert into groupByDemo(Name) values('John'); Query OK, 1 row affected (0.11 sec) mysql> insert into groupByDemo(Name) values('Sam'); Query OK, 1 row affected (0.17 sec) mysql> insert into groupByDemo(Name) values('Carol'); Query OK, 1 row affected (0.19 sec)
使用 select 语句显示表中的所有记录。
查询如下
mysql> select *from groupByDemo;
以下是输出 −
+----+-------+ | Id | Name | +----+-------+ | 1 | John | | 2 | Carol | | 3 | Carol | | 4 | Bob | | 5 | Bob | | 6 | Bob | | 7 | John | | 8 | John | | 9 | John | | 10 | Sam | | 11 | Carol | +----+-------+ 11 rows in set (0.00 sec)
这是按行数分组的查询
mysql> SELECT Counter, GROUP_CONCAT(Name SEPARATOR ', ') as AllName -> FROM (SELECT Name, COUNT(Name) as Counter -> FROM groupByDemo -> GROUP BY Name) tbl -> GROUP BY Counter -> ORDER BY Counter DESC;
以下是输出 −
+---------+------------+ | Counter | AllName | +---------+------------+ | 4 | John | | 3 | Carol, Bob | | 1 | Sam | +---------+------------+ 3 rows in set (0.00 sec)