Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Đếm số lần chuỗi xuất hiện trong cột MySQL

Tạo bảng demo

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

Chèn dữ liệu (Introduction to MySQL xuất hiện 3 lần)

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)

Hiển thị tất cả 8 bản ghi

mysql> select * from DemoTable704;

Kết quả

+--------------------------------------+
| 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)

Truy vấn đếm số lần "Introduction to MySQL" xuất hiện

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

Kết quả

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

Giải thích:

  • LIKE '%Introduction to MySQL%': Khớp chuỗi chứa từ khóa ở bất kỳ vị trí.
  • COUNT(*): Đếm số hàng thỏa mãn.

Mở rộng: Đếm tần suất tất cả giá trị:

SELECT SubjectName, COUNT(*) as TanSuat 
FROM DemoTable704 
GROUP BY SubjectName 
ORDER BY TanSuat DESC;

Kết quả:

+--------------------------------------+---------+
| SubjectName                          | TanSuat |
+--------------------------------------+---------+
| Introduction to MySQL                | 3       |
| Introduction to MongoDB              | 2       |
| Introduction to Java                 | 1       |
| Introduction to C                    | 1       |
| Introduction to Spring and Hibernate | 1       |
+--------------------------------------+---------+

Đếm từ khóa trong chuỗi văn bản (không phải khớp toàn cột): (LENGTH(cot) - LENGTH(REPLACE(cot, 'tu_khoa', ''))) / LENGTH('tu_khoa').