Selecionando as principais entradas que ocorrem no MySQL de uma tabela com valores duplicados?
Vamos primeiro criar uma tabela:
mysql> create table DemoTable610 (SubjectName varchar(100));
Query OK, 0 rows affected (0.63 sec)
Insira alguns registros na tabela usando o comando insert:
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)
Exiba todos os registros da tabela usando a instrução select:
mysql> select *from DemoTable610;
Isso produzirá a seguinte saída:
+-------------+
| SubjectName |
+-------------+
| MySQL |
| Java |
| MySQL |
| MongoDB |
| MySQL |
| MySQL |
| Java |
| MongoDB |
| C |
| C++ |
| MongoDB |
| MySQL |
| Java |
| Python |
| MySQL |
+-------------+
15 rows in set (0.00 sec)
Aqui está a consulta para selecionar apenas as entradas mais frequentes:
mysql> select SubjectName from ( select SubjectName from DemoTable610 group by SubjectName order by count(SubjectName) DESC LIMIT 2 ) AS tbl order by SubjectName;
Isso produzirá a seguinte saída:
+-------------+
| SubjectName |
+-------------+
| Java |
| MySQL |
+-------------+
2 rows in set (0.04 sec)