显示 MySQL 中某一列的重复记录数并对结果进行排序
mysqlmysqli database
为此,您需要使用 GROUP BY 作为列名。要获取计数,请使用 COUNT(*) 并使用 ORDER BY 对结果进行排序。以下是语法 −
select count(*) as anyAliasName from yourTableName group by yourColumnName order By yourAliasName DESC;
首先我们创建一个表 −
mysql> create table DemoTable ( Number int ); Query OK, 0 rows affected (0.82 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(110); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(120); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(120); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+--------+ | Number | +--------+ | 90 | | 100 | | 110 | | 90 | | 100 | | 90 | | 120 | | 100 | | 90 | | 120 | +--------+ 10 rows in set (0.00 sec)
以下查询显示重复记录的数量并对结果进行排序 −
mysql> select count(*) as Occured from DemoTable group by Number order By Occured DESC;
这将产生以下输出 −
+---------+ | Occured | +---------+ | 4 | | 3 | | 2 | | 1 | +---------+ 4 rows in set (0.00 sec)