在 MySQL 中对结果进行分组并显示在列表中?
mysqlmysqli database
为此,请使用 GROUP BY 和 ORDER BY −
select yourColumnName,count(*) as anyAliasName from yourTableName group by yourColumnName order by yourColumnName;
让我们创建一个表 −
mysql> create table demo7 −> ( −> id int NOT NULL AUTO_INCREMENT, −> first_name varchar(50) −> , −> primary key(id) −> ); Query OK, 0 rows affected (1.22 sec)
使用 insert 命令向表中插入一些记录 −
mysql> insert into demo7(first_name) values('John');
Query OK, 1 row affected (0.09 sec)
mysql> insert into demo7(first_name) values('David');
Query OK, 1 row affected (0.22 sec)
mysql> insert into demo7(first_name) values('John');
Query OK, 1 row affected (0.07 sec)
mysql> insert into demo7(first_name) values('Bob');
Query OK, 1 row affected (0.27 sec)
mysql> insert into demo7(first_name) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into demo7(first_name) values('David');
Query OK, 1 row affected (0.09 sec)
mysql> insert into demo7(first_name) values('John');
Query OK, 1 row affected (0.26 sec)
mysql> insert into demo7(first_name) values('John');
Query OK, 1 row affected (0.09 sec)
使用 select 语句显示表中的记录 −
mysql> select *from demo7;
这将产生以下输出 −
+----+------------+ | id | first_name | +----+------------+ | 1 | John | | 2 | David | | 3 | John | | 4 | Bob | | 5 | David | | 6 | David | | 7 | John | | 8 | John | +----+------------+ 8 rows in set (0.00 sec)
以下是在 MySQL 中对结果进行分组并显示在列表中的查询 −
mysql> select first_name,count(*) as frequency from demo7 group by first_name order by first_name;
这将产生以下输出 −
+------------+-----------+ | first_name | frequency | +------------+-----------+ | Bob | 1 | | David | 3 | | John | 4 | +------------+-----------+ 3 rows in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/
打印
下一节:如何合并 MySQL 结果? ❯❮ 上一节:MySQL Error ERROR 1099 (HY000): Table was locked with a READ lock and can't be updated

