How to find most popular word occurrences in MySQL?

后端 未结 6 2290
猫巷女王i
猫巷女王i 2021-02-13 11:38

I have a table called results with 5 columns.

I\'d like to use the title column to find rows that are say: WHERE title like \'%for sale%\

6条回答
  •  说谎
    说谎 (楼主)
    2021-02-13 11:51

    You can use ExtractValue in some interesting way. See SQL fiddle here: http://sqlfiddle.com/#!9/0b0a0/45

    We need only one table:

    CREATE TABLE text (`title` varchar(29));
    
    INSERT INTO text (`title`)
    VALUES
        ('cheap cars for sale'),
        ('house for sale'),
        ('cats and dogs for sale'),
        ('iphones and androids for sale'),
        ('cheap phones for sale'),
        ('house furniture for sale')
    ;
    

    Now we construct series of selects which extract whole words from text converted to XML. Each select extracts N-th word from the text.

    select words.word, count(*) as `count` from
    (select ExtractValue(CONCAT('', REPLACE(title, ' ', ''), ''), '//w[1]') as word from `text`
    union all
    select ExtractValue(CONCAT('', REPLACE(title, ' ', ''), ''), '//w[2]') from `text`
    union all
    select ExtractValue(CONCAT('', REPLACE(title, ' ', ''), ''), '//w[3]') from `text`
    union all
    select ExtractValue(CONCAT('', REPLACE(title, ' ', ''), ''), '//w[4]') from `text`
    union all
    select ExtractValue(CONCAT('', REPLACE(title, ' ', ''), ''), '//w[5]') from `text`) as words
    where length(words.word) > 0
    group by words.word
    order by `count` desc, words.word asc
    

提交回复
热议问题