在MySQL中计算多个文本串的出现次数?
您可以使用聚合函数count和if()来实现。为了理解概念,让我们创建一个表。创建表的查询如下所示
mysql> create table CountOccurrencesDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> TechnicalSubject varchar(100)
-> );
Query OK, 0 rows affected (0.68 sec)
现在您可以使用insert命令在表中插入一些记录。查询如下所示
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java');
Query OK, 1 row affected (0.14 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MongoDB');
Query OK, 1 row affected (0.13 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MySQL');
Query OK, 1 row affected (0.16 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MySQL');
Query OK, 1 row affected (0.10 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MySQL');
Query OK, 1 row affected (0.07 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java');
Query OK, 1 row affected (0.15 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java');
Query OK, 1 row affected (0.10 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java');
Query OK, 1 row affected (0.09 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java');
Query OK, 1 row affected (0.11 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MongoDB');
Query OK, 1 row affected (0.21 sec)
使用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)
阅读更多:MySQL 教程