您可以将GROUP BY与聚合函数COUNT()一起使用。让我们首先创建一个表-
create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Size ENUM('S','M','L','XL') );
使用插入命令在表中插入一些记录-
insert into DemoTable(Size) values('L'); insert into DemoTable(Size) values('S'); insert into DemoTable(Size) values('S'); insert into DemoTable(Size) values('M'); insert into DemoTable(Size) values('XL'); insert into DemoTable(Size) values('M'); insert into DemoTable(Size) values('M'); insert into DemoTable(Size) values('M'); insert into DemoTable(Size) values('XL');
使用select语句显示表中的所有记录-
select *from DemoTable;
这将产生以下输出-
+----+------+ | Id | Size | +----+------+ | 1 | L | | 2 | S | | 3 | S | | 4 | M | | 5 | XL | | 6 | M | | 7 | M | | 8 | M | | 9 | XL | +----+------+ 9 rows in set (0.00 sec)
以下是查询表中项目为ENUM的表中的项目的查询-
SELECT tbl.Size, COUNT(1) AS Frequency from DemoTable tbl group by tbl.Size;
这将产生以下输出-
+------+-----------+ | Size | Frequency | +------+-----------+ | L | 1 | | S | 2 | | M | 4 | | XL | 2 | +------+-----------+ 4 rows in set (0.00 sec)