views:

64

answers:

1

Hi, am looking for a query which will perform frequency ranking, so that the record which has maximum occurances of supplied "key word" will be listed top in the result.

my fields in the table are text and id. Can any one help me in this. Thanks in advance.

A: 

How about this: replace the keyword with nothing, then compare the new size to the old size. The difference, divided by the length of the keyword, is equal to the number of times it was found.

select id, text, 
    (length(text)-length(replace(text, 'KEYWORD', '')))/length('KEYWORD') 
from TableName 
where text like '%KEYWORD%';

This seems kind of flaky to me, but since you are trying to do it with SQL I could not think of a SQL string comparison function that returns the number of times a string was found.

MJB
If i am looking for a word 'bar' the above query will match 'barred','barb' which i dont want.Actually am using rails for my application , is there better alternative in rails?any suggestions will be appreciated.
kshama
Instead of just looking at 'KEYWORD', could you look for ' KEYWORD ' (that is, with spaces around it)? Are you looking at a series of words, a text document, or what? As for a rails answer, I can't help you there.
MJB
My column text is of mysql type text,which is a series of text which may span for 1000 words or more for few cases.if i use ' bar ' then no records are retrieved even if its there in the table. i found another query in one mysql forum which is SELECT id, text, MATCH (text) AGAINST ('keyword') AS score FROM contents WHERE MATCH (text) AGAINST ('keyword') INTO OUTFILE '/tmp/bar1.txt';this query works fine for other keywords like hopsital,but for bar its not giving any records,dont know what is the reason.
kshama
But the problem with query i mentioned is, if am searching for hopsital then records with Hospital (multiple times)is not given high score.how do i make the query case insensitive. will adding IN NATURAL LANGUAGE MODE will help (it is available only in mysql 5.1 right,but i have 5.0.67.do i have to upgrade?)
kshama