感谢youtube上的精彩视频,如果您愿意,可以访问here,我可以创建一个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')
我想知道是否可以根据数据库中短语内匹配的关键字数量来订购搜索结果?
答案 0 :(得分:6)
目前,您在代码中构建的查询在完成后看起来像这样:
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";