MySQL 查询获取字段中所有元素的数量?
mysqlmysqli database更新于 2025/5/26 3:24:17
为此,请使用 COUNT() 方法。让我们首先创建一个表 −
mysql> create table DemoTable -> ( -> ProductName varchar(100) -> ); Query OK, 0 rows affected (0.59 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('Product-1');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values('Product-2');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Product-3');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Product-3');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable values('Product-2');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Product-4');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Product-5');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Product-1');
Query OK, 1 row affected (0.11 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
这将产生以下输出 −
+-------------+ | ProductName | +-------------+ | Product-1 | | Product-2 | | Product-3 | | Product-3 | | Product-2 | | Product-4 | | Product-5 | | Product-1 | +-------------+ 8 rows in set (0.00 sec)
以下是获取字段中所有元素的数量的查询 −
mysql> select ProductName,count(ProductName) as TotalCount from DemoTable group by ProductName;
输出
这将产生以下输出 −
+-------------+------------+ | ProductName | TotalCount | +-------------+------------+ | Product-1 | 2 | | Product-2 | 2 | | Product-3 | 2 | | Product-4 | 1 | | Product-5 | 1 | +-------------+------------+ 5 rows in set (0.05 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

