MySQL查询来计数具有特定列的行?
让我们首先创建一个表-
mysql> create table DemoTable841( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value varchar(100) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable841(Value) values('X'); mysql> insert into DemoTable841(Value) values('Y'); mysql> insert into DemoTable841(Value) values('Y'); mysql> insert into DemoTable841(Value) values('Z'); mysql> insert into DemoTable841(Value) values('X'); mysql> insert into DemoTable841(Value) values('Z');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable841;
这将产生以下输出-
+----+-------+ | Id | Value | +----+-------+ | 1 | X | | 2 | Y | | 3 | Y | | 4 | Z | | 5 | X | | 6 | Z | +----+-------+ 6 rows in set (0.00 sec)
以下是对MySQL中具有特定列的行进行计数的查询-
mysql> select Value,Concat(COUNT(Value),' Times') from DemoTable841 group by Value;
这将产生以下输出-
+-------+-------------------------------+ | Value | Concat(COUNT(Value),' Times') | +-------+-------------------------------+ | X | 2 Times | | Y | 2 Times | | Z | 2 Times | +-------+-------------------------------+ 3 rows in set (0.04 sec)