[英]Count the number of multiple words occurrences within a text field in mysql
當在Risk表的記錄ID = 1中找到business_dictionary表中的每個關鍵字時,我想對它們的出現進行計數。
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.
--------------------------------------------------------------------------------
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:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.