统计 MySQL 表中具有特定值的三行或更多行
mysqlmysqli database
首先我们创建一个表 −
mysql> create table DemoTable -> ( -> UserId int -> ); Query OK, 0 rows affected (0.48 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.21 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
+----------+ | UserId | +----------+ | 10 | | 20 | | 30 | | 10 | | 10 | | 20 | | 30 | | 10 | | 20 | | 20 | | 40 | +----------+ 11 rows in set (0.00 sec)
以下查询用于计算 MySQL 表中具有特定值的行数,其中 3 行或更多行 −
mysql> select count(*) -> from (select UserId, count(*) as total -> from DemoTable group by UserId -> )tbl -> where total >=3;
这将产生以下输出,即值 10 和 20 出现三次或更多次。因此,计数为 2 个值 −
输出
+----------+ | count(*) | +----------+ | 2 | +----------+ 1 row in set (0.01 sec)