簡體   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