How to find most popular word occurrences in MySQL?

后端 未结 6 2288
猫巷女王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:46

    Update

    Idea taken from https://stackoverflow.com/a/17942691/98491

    This query works on my machine (MySQL 5.7), however Sqlfiddle reports an error. The basic idea is that you should either create a table with numbers from 1 to maximum word occurence (like 4) in your field or as I did, use a UNION 1 .. 4 for simplicity.

    CREATE TABLE products (
      `id` int,
      `name` varchar(45)
    );
    
    INSERT INTO products
        (`id`, `name`)
    VALUES
        (1, 'for sale'),
        (2, 'for me'),
        (3, 'for you'),
        (4, 'you and me')
    ;
    
    SELECT name, COUNT(*) as count FROM
    (
    SELECT
      product.id,
      SUBSTRING_INDEX(SUBSTRING_INDEX(product.name, ' ', numbers.n), ' ', -1) name
    FROM
      (
        SELECT 1 AS n
        UNION SELECT 2
        UNION SELECT 3
        UNION SELECT 4
      ) AS numbers
      INNER JOIN products product
      ON CHAR_LENGTH(product.name)
         -CHAR_LENGTH(REPLACE(product.name, ' ', ''))>=numbers.n-1
    ORDER BY
      id, n
    )
    AS result
    GROUP BY name
    ORDER BY count DESC
    

    Result will be

    for | 3
    you | 2
    me  | 2
    and | 1
    sale| 1
    

提交回复
热议问题