我正在尝试从用户在 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?
最佳答案
正如 Barmar 所说,您可以使用全文功能:
SELECT id, customer_id, phrase
FROM table
WHERE MATCH(phrase) AGAINST ('me wall like king apple');
如果还需要搜索另一列,请将其添加到MATCH
:
SELECT id, customer_id, phrase
FROM table
WHERE MATCH(phrase,keywords) AGAINST ('me wall like king apple');
编辑:
对于第 3 点,您可以使用相同的函数:
SELECT id, customer_id, phrase, MATCH(phrase,keywords) AGAINST ('me wall like king apple') as score
FROM table
WHERE MATCH(phrase,keywords) AGAINST ('me wall like king apple')
ORDER BY score
LIMIT 3;
此查询将返回三个最佳匹配
了解更多信息take a look to the manual
更新:
根据手册:
Some words are ignored in full-text searches:
Any word that is too short is ignored. The default minimum length of words that are found by full-text searches is four characters.
Words in the stopword list are ignored. A stopword is a word such as “the” or “some” that is so common that it is considered to have zero semantic value. There is a built-in stopword list, but it can be overwritten by a user-defined list.
您使用的是简短的单词进行搜索,这就是您没有得到任何结果的原因。
更新 09-09-14:
来自documentation :
If you modify full-text variables that affect indexing (
ft_min_word_len
,ft_max_word_len
, orft_stopword_file
), or if you change the stopword file itself, you must rebuild yourFULLTEXT
indexes after making the changes and restarting the server. To rebuild the indexes in this case, it is sufficient to do aQUICK
repair operation:mysql> REPAIR TABLE tbl_name QUICK;
因此,执行ALTER TABLE table ADD FULLTEXT(phrase, keywords);
后,您必须执行REPAIR TABLE tbl_name QUICK;
,但仅执行一次
关于php - 在mysql表中搜索5个关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25717935/