繁体   English   中英

在 MySQL 中搜索多个单词

[英]Search multiple words in MySQL

我正在使用 HTML 表单来允许用户在数据库表中查找条目:

   <form action="controller.php" method="get">
   <input type="text" name="word" id="word">

我的数据库中的表有一个名为关键字的列,其中包含多个值,因此我使用 SELECT 查询来选择具有与用户在表单中键入的内容相匹配的任何关键字的所有行。 所以 controller.php 包含这个查询:

$word= $_GET['word'];

$query = SELECT * FROM table WHERE table.keywords LIKE '%{$word}%

这工作正常,除非用户在搜索框中键入多个单词。 如何改变这一这样,当用户键入更多然后一个字到搜索框中,它会返回一个都行无论是在其关键字栏中的用户的话。

即,用户搜索“apples oranges”,并且查询返回在其关键字字段中包含“apples”或“oranges”的所有行。

你可以尝试 -

$words = explode(' ', $word);
$query = "SELECT * FROM table WHERE table.keywords IN (".implode(',', $words).")";

或者 -

$query = "SELECT * FROM table WHERE";
$conds = array();
foreach ($words as $val) {
    $conds[] = "table.keywords LIKE '%".$val."%'";
}
$query .= implode(' OR ', $conds);

如果需要,可以添加检查。

您可以使用正则表达式:

$words = explode(' ', $_GET['word']);
$regex = implode('|', $words);

$query = "SELECT * FROM table WHERE table.keywords REGEXP '{$regex}'";

我使用此代码并且工作正常

    $regcond = trim($_GET['word']);
    $regcond = preg_replace('!\s+!', ' ', $regcond); //change how many space beetwen word to one space
    $regcond = trim($regcond);
    $regcond = str_replace(" ",".+",$regcond); // change all space to .+ for search with regex
    $final_cond = 'SELECT * FROM table WHERE table.keywords REGEXP "' . $regcond . '"';
$words = explode(" ",$string);
$string = array_map(function(&$word){
    return "+".$word."*";
},$words);

$term = implode(" ",$string);
$query = "SELECT * FROM table_name WHERE MATCH(column_name) AGAINST('{$term}' IN BOOLEAN MODE)";

LIKE命令适用于单字串。 对于数据库中的高级搜索,请使用FULLTEXT搜索。

https://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

由于在 SQL 中无法搜索单个名称,请尝试基于空格拆分名称,例如 Heavens Road 并附加到字符串 ie ( '%Heavens%' ) OR ( %Road% ) 在最终查询中。

SELECT id, gps, street_name 
FROM streets 
WHERE street_name LIKE ('%Heavens%') OR (%Road%) 

例如,如果更多的术语是LIKE (%1term%) OR (%2term%) OR (%3term%) OR (%4term%)

正则表达式对我有用。

$str = $_GET['words']; 
$commonwords = 'a,an,and,I,it,is,do,does,for,from,go,how,the,this,are';// you dont want to search for these common words

$commonwords = explode(",", $commonwords);

$str = explode(" ", $str);

foreach($str as $value){
  if(!in_array($value, $commonwords)){ // remove the common words from search

    $query[] = $value;
  }
}   

$query = implode(" ", $query);// generate coma separated values 

$str2 =(explode(" ",$query));// convert the values to an array
$Words = implode('|',array_values($str2)).'';// generate values to be searched and make regex

"SELECT * FROM table_name WHERE `keywords` REGEXP '$Words'"

对我有用,用户搜索多个产品,每个产品都用空格分隔。 用户不必输入完整的单词

这是我的 PHP 解决方案,其中搜索字符串包含多个关键字,可以按任意顺序排列,可以由多个空格分隔,可能有重复,必须根据找到的关键字数量进行排名,并且 sql 注入安全。 假设表名为Topics,ID 为TopicID,TopicText 列中的文本和Keywords 列中的关键字,并且您的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 列作为上面的 regexp 目标。

  $word= $_GET['word'];
if (strpos($word, ' ') !== FALSE) {
    $wordArr = explode(' ', $word);
    $where = '';
    foreach ($wordArr AS $word) {
        $where .= " table.keywords LIKE '%{$word}%' OR";
    }
    $where = trim($where, 'OR');
} else {
    $where = "table.keywords LIKE '%{$word}%' ";
}
$query = "SELECT * FROM table WHERE $where";
echo $query;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM