代码之家  ›  专栏  ›  技术社区  ›  Ben

MySQL搜索查询,按最佳匹配对结果排序

  •  0
  • Ben  · 技术社区  · 15 年前

    我正在一个网站内的搜索引擎中工作,在那里访问者可以提供一些关键字,然后搜索引擎对数据表执行一些查询。

    我知道如何查询一个表,但是您如何构建一个提供完整结果列表的查询,以及数据表中每个匹配行的出现次数。

    比如说,我有一张简单的桌子,比如:

    id | title | desc
    -----------------
    1  | title 1 | some text with some text provding the user most likely no interesting info.
    
    2 | title 2 | some other text
    
    3 | title 3 | some third text saying some other crap.
    

    我要实现的是:当用户搜索“某些文本”时,我会得到如下结果:

    id | title | desc | noOfMatches
    -------------------------------
    1  | title 1 | ... | 4
    
    2  | title 3 | ... | 3
    
    3  | title 2 | ... | 2
    

    有人能帮我做这个吗?我不知道如何创建一个查询来计算一个查询中所提供单词的出现次数…

    2 回复  |  直到 13 年前
        1
  •  1
  •   Community CDub    7 年前

    也许这能帮助你: MySQL count matching words

        2
  •  1
  •   Quassnoi    15 年前

    使用 FULLTEXT 搜索:

    CREATE TABLE t_ft (id INT NOT NULL PRIMARY KEY, words VARCHAR(255) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET='utf8';
    
    CREATE FULLTEXT INDEX fx_ft_words ON t_ft (words);
    INSERT
    INTO    t_ft (id, words)
    VALUES  (1, 'some text with some text provding the user most likely no interesting info');
    
    INSERT
    INTO    t_ft (id, words)
    VALUES  (2, 'some other text');
    
    INSERT
    INTO    t_ft (id, words)
    VALUES  (3, 'some third text saying some other crap');
    
    INSERT
    INTO    t_ft
    SELECT  id + 3, 'complete nonsense'
    FROM    t_source
    LIMIT   1000;
    
    SELECT  *, MATCH(words) AGAINST('"some text"') AS relevance
    FROM    t_ft
    WHERE   MATCH(words) AGAINST('"some text"')
    ORDER BY
            relevance DESC;
    

    MATCH 将返回你可以使用的等级 ORDER BY .