使用单一 MySQL 查询计数并对行进行排序
首先,让我们创建一个表格 -
mysql> create table DemoTable783 ( FirstName varchar(100) ); Query OK, 0 rows affected (0.65 sec)
使用 insert 命令在表格中插入一些记录 -
mysql> insert into DemoTable783 values('Adam'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable783 values('Chris'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable783 values('Chris'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable783 values('Adam'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable783 values('Adam'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable783 values('Robert'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable783 values('Robert'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable783 values('Adam'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable783 values('Chris'); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表格中的所有记录 -
mysql> select *from DemoTable783;
将会得到以下输出 -
+-----------+ | FirstName | +-----------+ | Adam | | Chris | | Chris | | Adam | | Adam | | Robert | | Robert | | Adam | | Chris | +-----------+ 9 rows in set (0.00 sec)
以下是可在 MySQL 中计数和对行进行排序的查询 -
mysql> select FirstName, count(*) from DemoTable783 group by FirstName order by count(*) desc;
将会得到以下输出 -
+-----------+----------+ | FirstName | count(*) | +-----------+----------+ | Adam | 4 | | Chris | 3 | | Robert | 2 | +-----------+----------+ 3 rows in set (0.00 sec)
广告