【发布时间】:2014-09-08 05:29:52
【问题描述】:
我正在尝试从用户在 MySQL 表中输入的标签中搜索关键字,并根据匹配数返回最佳结果。
代码:
MySQL 结构:
id | keywords | phrase
1 | apple king pearl | I was eating an apple when the king hit me
2 | brush brute fancy | you fancy this brush?
3 | king queen kingdom | shall the queen obey the king or the kingdom?
PHP:
$keywords_raw='me wall like king apple' //define keywords based on the tags the user inputs
$keywords=explode(' ', $keywords_raw);
.... 这就是我卡住的地方。我的想法是:
搜索将针对每个关键字执行,例如“me”、“wall”、“like”等
对于每个关键字,它将在表格的每一行中搜索“关键字”和“短语”这两个列,并返回找到的匹配数。例如,搜索第一行输入的关键字将返回关键字“me”有 0 个匹配项,“wall”有 0 个匹配项,“like”有 0 个,“king”有 2 个,“apple”有 2 个。因此总匹配项为 2 +2 = 4。
- 最后,比较从所有行中找到的匹配总数,并选择匹配最多的前 3 行。
#2 的一个附带问题是如何忽略包含搜索关键字的单词,例如包含“king”但属于不同单词的“kingdom”。
更新:
根据有用的答案,我使用了全文搜索。
$keywords='bb';
$data['recommendation']=$this->db->query
("SELECT *, MATCH(keywords, phrase) AGAINST ('$keywords') as score
FROM game
WHERE MATCH(keywords, phrase) AGAINST ('$keywords')
ORDER BY score
LIMIT 3");
var_dump($data['recommendation']);
die;
由于某种原因,var_dump 返回一个空结果,没有找到任何行。但我确实在下表的至少 2 行中有短语“bb”,如下所示。
id | keywords | phrase
1 | bb king | I was eating an apple when bb the king hit me
2 | bb | you fancy this brush?
【问题讨论】:
-
这是一个全文搜索的工作。在 MySQL 文档中阅读它。
标签: php mysql search full-text-search sql-like