【问题标题】:Search multiple words in MySQL在 MySQL 中搜索多个单词
【发布时间】:2015-07-13 19:17:27
【问题描述】:

我正在使用 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”的行。

【问题讨论】:

  • 展开您的搜索词并循环遍历您创建多个 LIKE 语句并附加到查询的数组结果。
  • 如果使用全文搜索呢?这可以在 google 中对结果进行排序(按相关性)。

标签: php mysql


【解决方案1】:

你可以试试——

$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);

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

【讨论】:

  • 通配符在哪里? :)
  • 需要完全匹配。
  • 是的。对于这种情况,它需要完全匹配。也可以相应地生成查询。
  • @Daan 更新了答案。现在通配符可以使用了。
  • Thanx 中士,工作完美。只是出于兴趣,什么是通配符?
【解决方案2】:

你可以使用正则表达式:

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

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

【讨论】:

    【解决方案3】:

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

        $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 . '"';
    

    【讨论】:

      【解决方案4】:
      $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)";
      

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

        • 添加全文索引对 OP 没有帮助。
        【解决方案6】:

        由于 SQL 无法搜索单个名称,请尝试根据空格(例如 Heavens Road)拆分名称,并在最终查询中附加到字符串,即 ('%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%)

        【讨论】:

          【解决方案7】:

          这是我的 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 列作为上面的正则表达式目标。

          【讨论】:

            【解决方案8】:

            正则表达式为我做。

            $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'"
            

            适用于用户搜索多个产品,每个产品由空格分隔的情况。用户不必输入完整的单词

            【讨论】:

              【解决方案9】:
                $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;
              

              【讨论】:

              • 输入的字数是动态的,您的代码不是。
              • 如果包含两个以上的单词?
              • 不幸的是,这根本不是一个灵活的解决方案:(
              • 幸运的是,有一种灵活的方法可以遍历单词并构造查询。
              • @Daan,BOSE 中士,jeromegamez,bksi。感谢您的反馈,检查编辑的答案。
              猜你喜欢
              • 2011-10-06
              • 1970-01-01
              • 1970-01-01
              • 2013-12-18
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多