用于选择具有多次出现的值并显示其数量的 MySQL 查询
为此,使用 GROUP BY HAVING 子句。我们先创建一个表 −
mysql> create table DemoTable673( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value int ); Query OK, 0 rows affected (0.59 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable673(Value) values(10); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable673(Value) values(20); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable673(Value) values(10); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable673(Value) values(30); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable673(Value) values(20); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable673(Value) values(10); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable673(Value) values(10); Query OK, 1 row affected (0.28 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable673;
这将生成以下输出 −
+----+-------+ | Id | Value | +----+-------+ | 1 | 10 | | 2 | 20 | | 3 | 10 | | 4 | 30 | | 5 | 20 | | 6 | 10 | | 7 | 10 | +----+-------+ 7 rows in set (0.00 sec)
以下是仅显示具有多次出现的值的查询 −
mysql> select Id,count(*) as myValue from DemoTable673 group by Value having count(*) > 1;
这将生成以下输出 −
+----+---------+ | Id | myValue | +----+---------+ | 1 | 4 | | 2 | 2 | +----+---------+ 2 rows in set (0.00 sec)
广告