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

时间:2010-02-12 16:30:57

标签: mysql

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

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

所以说,我有简单的表格,如:

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

有人可以帮我这个吗?我不知道如何创建一个可以计算no的查询。查询中提供的单词的后缀......

2 个答案:

答案 0 :(得分:1)

也许这会对你有所帮助: MySQL count matching words

答案 1 :(得分:1)

使用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中可以使用的排名。

相关问题