[英]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.