2017-05-13 141 views
0

我對MySQL很陌生。我需要計算MySQL表/列中特定字的出現次數。如何計算Mysql數據庫行中特定單詞的出現次數?

我通過另一篇文章@Raging公牛,只提供一個特定的詞的計數碰到下面的代碼。

SELECT name,(CHAR_LENGTH(description)- 
    CHAR_LENGTH(REPLACE(description,' is ','')))/CHAR_LENGTH(' is ') AS 
TotalCount 
FROM TableName 
GROUP BY name 

有人能幫我把它對齊多個單詞來計算。例如,我要計算「是」,「如」,「是」,「如何」。

+2

將所期望的結果是什麼樣的?而看到https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-查詢 – Strawberry

+0

看到有一個編輯按鈕 – Strawberry

+0

字| S計數 -s是| S 10 -s如何| S 15 -s得s | 20 –

回答

0

嘗試使用LENGTH代替CHAR_LENGTH和字符串截斷空格,如:

SELECT name, 
    ROUND ( 
     (
      LENGTH(description) 
      - LENGTH(REPLACE(description, "is", "")) 
     )/LENGTH("is")   
    ) AS count 
FROM TableName 

更新

要算多的話,你可以寫呈三角ROUND查詢,並把它們相加,如:

SELECT name, 
    SELECT(
     ROUND((LENGTH(description)- LENGTH(REPLACE(description, "is", "")))/LENGTH("is")) + 
     ROUND((LENGTH(description)- LENGTH(REPLACE(description, "This", "")))/LENGTH("This")) + 
     ROUND((LENGTH(description)- LENGTH(REPLACE(description, "That", "")))/LENGTH("That")) 
     ) AS `count` 
FROM TableName 

更新2

這裏的查詢來獲取算作單獨列:

SELECT name, 
ROUND((LENGTH(description)- LENGTH(REPLACE(description, "is", "")))/LENGTH("is")) AS 'is count', 
ROUND((LENGTH(description)- LENGTH(REPLACE(description, "this", "")))/LENGTH("this")) AS 'this count', 
ROUND((LENGTH(description)- LENGTH(REPLACE(description, "by", "")))/LENGTH("by")) AS 'by count' 

FROM表名

更新3

下面是查詢來獲取單詞彙總數:

SELECT 'is', SUM(ROUND((LENGTH(description)- LENGTH(REPLACE(description, "is", "")))/LENGTH("is"))) AS `count` FROM TableName 

UNION 

SELECT 'this', SUM(ROUND((LENGTH(description)- LENGTH(REPLACE(description, "this", "")))/LENGTH("this"))) AS `count` FROM TableName 

UNION 

SELECT 'by', SUM(ROUND((LENGTH(description)- LENGTH(REPLACE(description, "by", "")))/LENGTH("by"))) AS `count` FROM TableName 

這裏的SQL Fiddle

+0

我需要多個單詞的計數。至於你的代碼,我需要像 -test -is - 多字的計數先生 –

+0

只在代碼中,「is」正在計算。我需要多個詞來計算。 喜歡,在這句話:你今天過得怎麼樣? 結果應該有 - How:1;是:1;您; 1 –

+0

@JohnWix添加了對多個單詞進行計數的查詢。 –

1

MySQL是不適合這樣的事情。但是,您可以將這些值一起添加。我正確的方法就是這樣;

select ((length(concat(' ', description, ' ')) - length(replace(concat(' ', description, ' '), ' is ', ''))/length(' is ') + 
     (length(concat(' ', description, ' ')) - length(replace(concat(' ', description, ' '), ' as ', ''))/length(' as ') + 
     (length(concat(' ', description, ' ')) - length(replace(concat(' ', description, ' '), ' was ', ''))/length(' was ') + 
     (length(concat(' ', description, ' ')) - length(replace(concat(' ', description, ' '), ' how ', ''))/length(' how ') 
     ) 
from t ; 

請注意,在開始和結束處使用空格來捕捉說明開頭和結尾處的單詞。此外,這假設只有空格用於分隔單詞。

+0

它似乎給錯誤@Gordon Linoff –

+0

@Strawberry如何包括正則表達式。代碼請。我很新 –

+0

@JohnWix我想我正在混合MariaDB - 它有W ider支持正則表達式。 – Strawberry

0
select count(adm_no) from class_manager 

嘗試這其中adm_no是列名和class_manager是表

相關問題