我将使用 MATCH-AGAINST,这对于像搜索引擎这样的 MySQL 优化搜索应该更好。您应该查看全文搜索:http: //dev.mysql.com/doc/refman/5.5/en//fulltext-search.html
注意:在 MySQL 表中,应将索引编辑为数据库表中关键字行的 FULLTEXT。这将为搜索提供更好的性能。
例子:
输入关键字示例:
$keywords = '+Word+Word2+Word3';
SELECT p.page_url AS url,
COUNT(*) AS occurrences, MATCH('w.word_word') AGAINST ('$keywords') as keyword FROM page p, occurrence o, w.word WHERE MATCH
('w.word_word') AGAINST('{$keywords}' IN
BOOLEAN MODE)
AND p.page_id = o.page_id AND w.word_id = o.word_id
GROUP BY p.page_id
ORDER BY occurrences DESC
LIMIT $results
如果您的查询未优化(组太多、where 子句和条件),则在其他去优化模式下或有降低服务器性能的风险。而不是这个,您可以在 MySQL 中使用 REGULAR EXPRESSION 例如:
REGEXP "/(honda)|(jazz)|(manual)/"
这也将使用正则表达式获得良好的性能(不推荐用于大型数据库):
做一个循环并计算它而不是放入 REGEXP:
$keywords = "keyword1,keyword2,keyword3";
$expl = explode("," $keywords);
if (count($expl) == 1)
{
$all = w.word_word REGEXP = '[[:<:]]$keywords[[:>:]]';
}
else
{
$all = '';
foreach ($expl as $keyone)
{
$all .= 'OR '.w.word_word REGEXP = '[[:<:]]$keyone[[:>:]]';
}
}
$sql = 'SELECT p.page_url AS url,
COUNT(*) AS occurrences
FROM page p, word w, occurrence o
WHERE p.page_id = o.page_id AND
w.word_id = o.word_id AND
$all
GROUP BY p.page_id
ORDER BY occurrences DESC
LIMIT $results';
$result_query = mysql_query($sql);