计算mysql中文本字段中多个单词出现次数

时间:2015-07-03 11:52:51

标签: mysql count

我想在business_dictionary表中找到每个关键字的出现次数,当它在Risk表中的记录ID = 1中找到时。

business_dictionary表:

ID | Keyword
----------------
1  | manage
2  | service
3  | objectives
4  | success
5  | achieved
6  | management
7  | skills
----------------

风险表:

ID | Description
--------------------------------------------------------------------------------
1  | The quality of service has to be our first priority because the client is here to receive our service. So we have to manage all the areas supporting this service with efficiency.
--------------------------------------------------------------------------------

1 个答案:

答案 0 :(得分:0)

See results at bottom

DELIMITER $$ 

CREATE FUNCTION `getCount`(myStr VARCHAR(1000), myword VARCHAR(100)) 
RETURNS INT 

BEGIN 
DECLARE cnt INT DEFAULT 0; 
DECLARE result INT DEFAULT 1; 
WHILE (result > 0) 
DO SET result = INSTR(myStr, myword); 
IF(result > 0) THEN SET cnt = cnt + 1; 
SET myStr = SUBSTRING(myStr, result + LENGTH(myword)); 
END IF; 
END WHILE; 
RETURN cnt; 
END$$ 
DELIMITER ;

create table business_dictionary
(
    id int auto_increment primary key,
    keyword varchar(40) not null
);

insert business_dictionary (keyword) values ('manage'),('service'),('objectives'),('success'),('achieved'),('management'),('skills')

create table risk
(
    id int auto_increment primary key,
    description varchar(1000) not null
);

insert risk (description) values ('The quality of service blah blah service blah manage blah service with blah');

-- take advantage of ugly non-explicit join finally

select bd.keyword,getCount(r.description,bd.keyword) as theCount
from business_dictionary bd,risk r
where r.id=1
order by theCount desc

keyword         theCount
service         3
manage          1
skills          0
objectives      0
success         0
achieved        0
management      0

function written above shamelessly poached from:

Count occurrences of a word in a row in MySQL