这是我的 PHP 解决方案,其中搜索字符串包含多个关键字,可以按任意顺序排列,可以用多个空格分隔,可以有重复,必须根据找到的关键字数量进行排名,并且是 sql 注入安全的。假设表名为 Topics,ID 为 TopicID,文本在 TopicText 列,关键字在关键字列,您的 mySQL 连接是 $dbConn
//convert search string to lowercase - will do case insensitive search later
$words = trim(strtolower($_GET['k']));
//remove punctuation and wildcards
$words = str_replace(array('*', '?', '-', '.', '/', '(', ')', '+', '&'), '', $words);
//turn the string into an array of unique words
$words = array_unique(explode(' ', $words));
//strip the words we are not interested in
$stopWords = array('', '*', '?', 'a', 'about', 'an', 'and','are', 'as', 'at', 'be', 'by', 'for', 'from', 'how', 'in', 'is', 'it', 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'what', 'when', 'where', 'who', 'will', 'with');
foreach($stopWords as $word) {
if (($key = array_search($word, $words)) !== false) unset($words[$key]);
}
//build SQL statement
$sql = "select TopicText, Score from (select TopicID, 0";
foreach($words as $word) {
if($word>'') $sql .= "+if(Keywords regexp '" . $dbConn->real_escape_string($word) . "',1,0)";
}
$sql .= " as Score from Topics) T join Topics TT on TT.TopicID = T.TopicID where T.Score>0 order by Score desc";
如果您没有包含关键字的列,可以使用 TopicText 列作为上面的正则表达式目标。