您可以if()
为此使用聚合函数计数。为了理解这个概念,让我们创建一个表。创建表的查询如下
mysql> create table CountOccurrencesDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> TechnicalSubject varchar(100) -> );
现在,您可以使用insert命令在表中插入一些记录。查询如下
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java'); mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MongoDB'); mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MySQL'); mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MySQL'); mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MySQL'); mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java'); mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java'); mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java'); mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java'); mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MongoDB');
使用select语句显示表中的所有记录。查询如下
mysql> select *from CountOccurrencesDemo;
以下是输出
+----+------------------+ | Id | TechnicalSubject | +----+------------------+ | 1 | Java | | 2 | MongoDB | | 3 | MySQL | | 4 | MySQL | | 5 | MySQL | | 6 | Java | | 7 | Java | | 8 | Java | | 9 | Java | | 10 | MongoDB | +----+------------------+ 10 rows in set (0.00 sec)
以下是对MySQL中多次出现的文本进行计数的查询
mysql> select count(if(tbl.TechnicalSubject LIKE '%Java%',1,null)) as JavaOccurrence, -> count(if(tbl.TechnicalSubject LIKE '%MySQL%',1,null)) as MySQLOccurrence, -> count(if(tbl.TechnicalSubject LIKE '%MongoDB%',1,null)) as MongoDBOccurrence -> from CountOccurrencesDemo tbl;
以下是输出
+----------------+-----------------+-------------------+ | JavaOccurrence | MySQLOccurrence | MongoDBOccurrence | +----------------+-----------------+-------------------+ | 5 | 3 | 2 | +----------------+-----------------+-------------------+ 1 row in set (0.05 sec)