从具有重复值的表中选择MySQL中出现次数最高的条目?
让我们首先创建一个表-
create table DemoTable610 (SubjectName varchar(100));
使用插入命令在表中插入一些记录-
insert into DemoTable610 values('MySQL'); insert into DemoTable610 values('Java'); insert into DemoTable610 values('MySQL'); insert into DemoTable610 values('MongoDB'); insert into DemoTable610 values('MySQL'); insert into DemoTable610 values('MySQL'); insert into DemoTable610 values('Java'); insert into DemoTable610 values('MongoDB'); insert into DemoTable610 values('C'); insert into DemoTable610 values('C++'); insert into DemoTable610 values('MongoDB'); insert into DemoTable610 values('MySQL'); insert into DemoTable610 values('Java'); insert into DemoTable610 values('Python'); insert into DemoTable610 values('MySQL');
使用select语句显示表中的所有记录-
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)
这是仅选择出现次数最高的条目的查询-
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)