MySql: Count amount of times the words occur in a column

后端 未结 5 1424
心在旅途
心在旅途 2021-01-06 19:13

For instance, if I have data in a column like this

data
I love book
I love apple
I love book
I hate apple
I hate apple

How can I get result

5条回答
  •  忘掉有多难
    2021-01-06 19:38

    This query is going to take a long time to run if your table is of any decent size. It may be better to keep track of the counts in a separate table and update that table as values are inserted or, if real time results are not necessary, to only run this query every so often to update the counts table and pull your data from it. That way, you're not spending minutes to get data from this complex query.

    Here's what I've for you so far. It's a good start. The only thing you need to do is modify it to iterate through the words in each row. You could use a cursor or a subquery.

    Create test table:

    create table tbl(str varchar(100) );
    insert into tbl values('data');
    insert into tbl values('I love book');
    insert into tbl values('I love apple');
    insert into tbl values('I love book');
    insert into tbl values('I hate apple');
    insert into tbl values('I hate apple');
    

    Pull data from test table:

    SELECT DISTINCT str AS Word, COUNT(str) AS Frequency FROM tbl GROUP BY str;
    

提交回复
热议问题