在 MySQL 中计算单独文本的多次出现次数?

mysqlmysqli database

您可以使用聚合函数 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)

相关文章