ใช้ Logic: (LENGTH(str) - LENGTH(REPLACE(str, 'substr', ''))) / LENGTH('substr')
สร้างตารางและข้อมูล
mysql> CREATE TABLE StringOccurrenceDemo (
-> Cases VARCHAR(100),
-> StringValue VARCHAR(500)
-> );
mysql> INSERT INTO StringOccurrenceDemo VALUES
-> ('First', 'This is MySQL Demo and MySQL is an open source RDBMS'),
-> ('Second', 'There is no'),
-> ('Third', 'There is MySQL,Hi MySQL,Hello MySQL');
Query นับ 'MySQL'
mysql> SELECT
-> Cases,
-> StringValue,
-> ROUND((LENGTH(StringValue) - LENGTH(REPLACE(StringValue, 'MySQL', ''))) / LENGTH('MySQL'))
-> AS NumberOfOccurrenceOfMySQL
-> FROM StringOccurrenceDemo;
ผลลัพธ์:
+--------+------------------------------------------------------+---------------------------+ | Cases | StringValue | NumberOfOccurrenceOfMySQL | +--------+------------------------------------------------------+---------------------------+ | First | This is MySQL Demo and MySQL is an open source RDBMS | 2 | | Second | There is no | 0 | | Third | There is MySQL,Hi MySQL,Hello MySQL | 3 | +--------+------------------------------------------------------+---------------------------+
ฟังก์ชันช่วย (MySQL 8.0+)
-- ใช้ REGEXP_COUNT (MySQL 8.0.4+) SELECT REGEXP_COUNT(StringValue, 'MySQL') FROM StringOccurrenceDemo;
ข้อจำกัด
- Case-sensitive (MySQL Default Collation)
- Overlapping matches ไม่นับ (เช่น 'aaa' หา 'aa' = 1 ไม่ใช่ 2)
- NULL input → NULL output (ใช้ COALESCE)
Performance: สำหรับข้อมูลมาก ควร Full-Text Search หรือ Pre-compute Count ไว้ใน Column แยก