从具有重复值的数据表中选择 MySQL 中出现次数最多的条目?
让我们首先创建一个表 −
mysql> create table DemoTable610 (SubjectName varchar(100)); Query OK, 0 rows affected (0.63 sec)
使用插入命令在表中插入一些记录 −
mysql> insert into DemoTable610 values('MySQL'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable610 values('Java'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable610 values('MySQL'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable610 values('MongoDB'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable610 values('MySQL'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable610 values('MySQL'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable610 values('Java'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable610 values('MongoDB'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable610 values('C'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable610 values('C++'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable610 values('MongoDB'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable610 values('MySQL'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable610 values('Java'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable610 values('Python'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable610 values('MySQL'); Query OK, 1 row affected (0.15 sec)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable610;
这将产生以下输出 −
+-------------+ | SubjectName | +-------------+ | MySQL | | Java | | MySQL | | MongoDB | | MySQL | | MySQL | | Java | | MongoDB | | C | | C++ | | MongoDB | | MySQL | | Java | | Python | | MySQL | +-------------+ 15 rows in set (0.00 sec)
以下是仅选择 Top 个显示次数最多的条目的查询 −
mysql> select SubjectName from ( select SubjectName from DemoTable610 group by SubjectName order by count(SubjectName) DESC LIMIT 2 ) AS tbl order by SubjectName;
这将产生以下输出 −
+-------------+ | SubjectName | +-------------+ | Java | | MySQL | +-------------+ 2 rows in set (0.04 sec)
广告