如何在自己的 MySQL 查询中获取一个值的所有出现的次数?
为此,你可以使用子查询。我们首先创建一个表格 -
mysql> create table DemoTable -> ( -> Value int -> ); Query OK, 0 rows affected (0.61 sec)
使用插入命令向表中插入一些记录 -
mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.36 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.20 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
输出
这将产生以下输出 -
+-------+ | Value | +-------+ | 20 | | 30 | | 20 | | 40 | | 30 | | 20 | +-------+ 6 rows in set (0.00 sec)
以下是获取值总次数的查询 -
mysql> select tbl.Value,(SELECT COUNT(*) from DemoTable where Value = tbl.Value) AS Occurrence from DemoTable tbl;
输出
这将产生以下输出 -
+-------+------------+ | Value | Occurrence | +-------+------------+ | 20 | 3 | | 30 | 2 | | 20 | 3 | | 40 | 1 | | 30 | 2 | | 20 | 3 | +-------+------------+ 6 rows in set (0.00 sec)
广告