为此,您可以将GROUP BY子句与一起使用IN()
。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(100) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Name) values('John'); mysql> insert into DemoTable(Name) values('Chris'); mysql> insert into DemoTable(Name) values('David'); mysql> insert into DemoTable(Name) values('Chris'); mysql> insert into DemoTable(Name) values('Chris'); mysql> insert into DemoTable(Name) values('John'); mysql> insert into DemoTable(Name) values('Carol'); mysql> insert into DemoTable(Name) values('Sam');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+-------+ | Id | Name | +----+-------+ | 1 | John | | 2 | Chris | | 3 | David | | 4 | Chris | | 5 | Chris | | 6 | John | | 7 | Carol | | 8 | Sam | +----+-------+ 8 rows in set (0.00 sec)
现在,通过单个查询计算一列中特定值的出现次数-
mysql> select Name,count(*) AS Occurrences from DemoTable -> where Name in('John','Chris') group by Name;
这将产生以下输出-
+-------+-------------+ | Name | Occurrences | +-------+-------------+ | John | 2 | | Chris | 3 | +-------+-------------+ 2 rows in set (0.00 sec)