how to count the occurence of a word in multiple rows of a mysql db

一曲冷凌霜 提交于 2019-12-11 07:17:37

问题


i am looking for some help with counting the number of occurences in multiple rows of a mysql db.the purpose is for creting a search engine like google but only for my website

the scheme is to display the entry which has the most number of occurences of the word at the very top

for eg . the user searches for the word key.the records are searched and the data is shown in order of the number of occurences

 1.this is a key which is a test key and also the profile key (3 occurences)
 2.key give me a key (2 occurences)
 ....and so on...

is this the best approach?

SELECT (LENGTH(daya) - LENGTH(REPLACE(data, 'key', ''))) / LENGTH('key') AS `count` ORDER BY `count` DESC // data is the column name and key is the word

or is there a better one

Note:i dont want to use Like % %. also i want to show the number of times the word has occured like so the word key has occured 3 times.Could i use count()


回答1:


You can add the count in ORDER BY clause.

Try this way:

SELECT *,(LENGTH(data) - LENGTH(REPLACE(data, 'key', ''))) / LENGTH('key') as cnt
FROM TableName
ORDER BY ((LENGTH(data) - LENGTH(REPLACE(data, 'key', ''))) / LENGTH('key')) DESC

To get the records of 2 occurences, you can use HAVING clause:

SELECT *,(LENGTH(data) - LENGTH(REPLACE(data, 'key', ''))) / LENGTH('key') as cnt
FROM TableName
HAVING cnt=2
ORDER BY ((LENGTH(data) - LENGTH(REPLACE(data, 'key', ''))) / LENGTH('key')) DESC



回答2:


Your approach is fine, but you can dispense with the division by using one character more or less:

SELECT (LENGTH(REPLACE(data, 'key', 'key1')) - LENGTH(data)) as `count`
FROM table t
ORDER BY `count` DESC // data is the column name and key is the word

If you want values that appear "n" times, using can use the having clause in MySQL:

SELECT (LENGTH(REPLACE(data, 'key', 'key1')) - LENGTH(data)) as `count`
FROM table t
HAVING `count` = 2
ORDER BY `count` DESC // data is the column name and key is the word

This use of the having clause is a MySQL extension and will not work in other databases.



来源:https://stackoverflow.com/questions/23711851/how-to-count-the-occurence-of-a-word-in-multiple-rows-of-a-mysql-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!