計一下 MySQL 中 VARCHAR 欄位中某個字串的出現次數
為了計算 VARCHAR 中某個字串的出現次數,我們可以使用長度減法的邏輯。我們首先會藉助建立命令來建立一個表。
mysql> create table StringOccurrenceDemo -> ( -> Cases varchar(100), -> StringValue varchar(500) -> ); Query OK, 0 rows affected (0.56 sec)
執行完上述表格之後,我們會向表格中插入記錄。查詢如下 -
mysql> insert into StringOccurrenceDemo values('First','This is MySQL Demo and MySQL is an open source RDBMS'); Query OK, 1 row affected (0.07 sec) mysql> insert into StringOccurrenceDemo values('Second','There is no'); Query OK, 1 row affected (0.20 sec) mysql> insert into StringOccurrenceDemo values('Third','There is MySQL,Hi MySQL,Hello MySQL'); Query OK, 1 row affected (0.17 sec)
藉助 select 語句顯示所有記錄。
mysql> select *From StringOccurrenceDemo;
下面是輸出。
+--------+------------------------------------------------------+ | Cases | StringValue | +--------+------------------------------------------------------+ | First | This is MySQL Demo and MySQL is an open source RDBMS | | Second | There is no | | Third | There is MySQL,Hi MySQL,Hello MySQL | +--------+------------------------------------------------------+ 3 rows in set (0.00 sec)
以下是計算字串“MySQL”出現次數的查詢。結果會顯示在列“NumberOfOccurrenceOfMySQL”中
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 | 0 | | Third | There is MySQL,Hi MySQL,Hello MySQL | 3 | +--------+------------------------------------------------------+---------------------------+ 3 rows in set (0.05 sec)
上述輸出表明我們已經找到了字串“MySQL”出現次數。
廣告