獲取字串在 MySQL 列中出現的次數


我們首先建立一個表 -

mysql> create table DemoTable704 (SubjectName text);
Query OK, 0 rows affected (0.58 sec)

使用 insert 命令插入一些記錄 -

mysql> insert into DemoTable704 values('Introduction to MySQL');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable704 values('Introduction to MongoDB');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable704 values('Introduction to MySQL');
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable704 values('Introduction to Java');
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable704 values('Introduction to MongoDB');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable704 values('Introduction to MySQL');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable704 values('Introduction to C');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable704 values('Introduction to Spring and Hibernate');
Query OK, 1 row affected (0.12 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable704;

這將產生以下輸出 -

+--------------------------------------+
| SubjectName                          |
+--------------------------------------+
| Introduction to MySQL                |
| Introduction to MongoDB              |
| Introduction to MySQL                |
| Introduction to Java                 |
| Introduction to MongoDB              |
| Introduction to MySQL                |
| Introduction to C                    |
| Introduction to Spring and Hibernate |
+--------------------------------------+
8 rows in set (0.00 sec)

以下是對字串在列中出現的次數進行計數的查詢 -

mysql> SELECT COUNT(*) from DemoTable704 WHERE SubjectName LIKE '%Introduction to MySQL%';

這將產生以下輸出 -

+----------+
| COUNT(*) |
+----------+
| 3        |
+----------+
1 row in set (0.00 sec)

更新於:21-Aug-2019

309 次瀏覽

kickstart職業

完成課程獲得認證

開始
廣告