从 MySQL 表中计算包含特定值的三行或三行及以上的数据行
我们首先创建一个表 -
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 行或 3 行及以上并且包含特定值的数据行的数量 -
mysql> select count(*) -> from (select UserId, count(*) as total -> from DemoTable group by UserId -> )tbl -> where total >=3;
这将产生以下输出,即值 10 和 20 出现 3 次或 3 次以上。因此,计数针对 2 个值 -
输出
+----------+ | count(*) | +----------+ | 2 | +----------+ 1 row in set (0.01 sec)
广告