3

感谢 youtube 上的精彩视频,如果您愿意,可以在这里访问,我能够创建一个 php 搜索引擎。下面是代码:

<?php


//connected to DB

      foreach (array('questioncontent') as $varname) {
        $questioncontent = (isset($_GET[$varname])) ? $_GET[$varname] : '';
      }

?>

<form action="previousquestions.php" method="get">
      <p>Search: <input type="text" name="questioncontent" value="<?php echo $questioncontent; ?>" /></p>
      <p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
      </form>

<?php 

if (isset($_GET['searchQuestion'])) {

$searchquestion = $questioncontent;
$terms = explode(" ", $searchquestion);

              $questionquery = "SELECT * FROM Question WHERE ";

              foreach ($terms as $each){
               $i++;   

               if ($i == 1){
               $questionquery .= "QuestionContent LIKE '%$each%' ";
          } else{
               $questionquery .= "OR QuestionContent LIKE '%$each%' ";

              }

          }

      $questionnum = mysql_num_rows($questionresult = mysql_query($questionquery));

        else if($questionnum !=0){

      $output = "";
$output .= "
    <table border='1'>
      <tr>
      <th>Question</th>
      </tr>
";
        while ($questionrow = mysql_fetch_array($questionresult)) {
$output .= "
      <tr>
      <td>{$questionrow['QuestionContent']}</td>
      </tr>";
        }
        $output .= "        </table>";

        echo $output;

  }

}

  mysql_close();

?>

现在我有一个问题,如果可能的话,如何对搜索结果进行排序。假设在数据库中我有这 3 个语句:

My name
My name is Mayur Patel
My name is Patel

现在假设我在搜索框中输入“姓名 Mayur Patel”,我希望对结果进行排序,以便它首先显示包含所有这些关键词的任何行,然后在显示所有这些行之后再显示这些行其中包含这些关键字的部分数量(一个一个地敲掉一个关键字),因此搜索结果将按以下顺序显示:

My name is Mayur Patel (all keywords match in this phrase)
My name is Patel (2 keywords match this phrase which are 'name' and 'Patel')
My name (1 keyword match this phrase which is 'name')

我想知道是否可以根据数据库中短语中匹配的关键字数量对搜索结果进行排序?

4

1 回答 1

7

目前,您的内置代码查询在完成后看起来像这样:

SELECT * FROM Question WHERE
QuestionContent LIKE '%name%'
OR QuestionContent LIKE '%Mayur%'
OR QuestionContent LIKE '%Patel%'

要获得您正在寻找的结果,您可以添加如下排序子句,该子句将以类似的方式从关键字列表中生成:

ORDER BY
IF(QuestionContent LIKE '%name%',1,0)+
IF(QuestionContent LIKE '%Mayur%',1,0)+
IF(QuestionContent LIKE '%Patel%',1,0) DESC

基本上,它通过说是否匹配来计算有多少关键字匹配,为关键字计数贡献一个,否则贡献 0。所以最后,这将产生 3、2、1 作为计数,并按降序排序DESC因此,匹配关键字最多的条目首先出现。

演示:http ://www.sqlfiddle.com/#!2/eaabc/2


编辑:正如所承诺的,这是一种在 PHP 代码中实现的方法:

$questionquery = "SELECT * FROM Question WHERE ";
foreach ($terms as $each) {
    $i++;   

    if ($i == 1){
        $questionquery .= "QuestionContent LIKE '%$each%' ";
    } else {
        $questionquery .= "OR QuestionContent LIKE '%$each%' ";
    }
}

$questionquery .= " ORDER BY ";
$i = 0;
foreach ($terms as $each) {
    $i++;

    if ($i != 1)
        $questionquery .= "+";
    $questionquery .= "IF(QuestionContent LIKE '%$each%',1,0)";
}
$questionquery .= " DESC";
于 2012-05-24T20:14:11.810 回答