3

I have a mysql table it has lot of words on it.

  • Hai.
  • Am i
  • hai
  • joe
  • This
  • Those
  • hai

In at above example "hi" is occurring three times I want to create a query which will look at this table and sort out most occurred words.

2 Answers2

1

You need to use GROUP BY clause and COUNT function.

SELECT word, COUNT(*) count FROM your_table GROUP BY word ORDER BY count DESC LIMIT 0,3;

Possible output:

+------+-------+
| word | count |
+------+-------+
| hai  | 2     |
| Hai. | 1     |
| This | 1     |
+------+-------+

If you want MySQL to treat hai and Hai. as the same word, you should strip all non-alpha characters before grouping. See MySQL: how to remove all non-alpha numeric characters from a string?. Then, based on method from this answer it will look like this:

SELECT LOWER(alphanum(word)) word, COUNT(*) count FROM your_table 
GROUP BY LOWER(alphanum(word)) ORDER BY count DESC LIMIT 0,3;

And possible result:

+------+-------+
| word | count |
+------+-------+
| hai  | 3     |
| this | 1     |
| joe  | 1     |
+------+-------+
Community
  • 1
  • 1
fracz
  • 20,536
  • 18
  • 103
  • 149
0

You need to compose a sql statement using the group by method that will group like things together. Something like this should get you started

select word, count(word) 
from table 
group by word 
order by count(word) desc
Dave Bennett
  • 10,996
  • 3
  • 30
  • 41
habib ul haq
  • 824
  • 6
  • 13