如何计算mysql数据库的多行中一个单词的出现次数

时间:2014-05-17 13:23:37

标签: php mysql sql instances

我正在寻找一些帮助来计算mysql db的多行中出现的次数。目的是创建像google这样的搜索引擎,但仅用于我的网站

该方案是显示最顶层出现的词数最多的条目

例如。用户搜索单词key.the搜索记录,数据按出现次数的顺序显示

 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...

这是最好的方法吗?

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

还是有更好的

注意:我不想使用Like % %。我也希望显示单词出现的次数the word key has occured 3 times。我可以使用count()

2 个答案:

答案 0 :(得分:1)

您可以在ORDER BY子句中添加计数。

尝试这种方式:

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

要获取2次出现的记录,可以使用HAVING子句:

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

答案 1 :(得分:0)

你的方法很好,但你可以或多或少地使用一个角色来免除分裂:

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

如果您希望值出现“n”次,则可以使用MySQL中的having子句:

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

having子句的使用是MySQL扩展,不适用于其他数据库。