如何在MySQL中消除重复的搜索结果?

时间:2014-09-26 07:27:07

标签: php mysql sql

我在使用PHP和SQL从数据库显示文本时遇到了一些麻烦。下面是一个类似于我的脚本。

$search_split = explode(" ", $search); //$search is what user entered
foreach ($search_split as $searcharray) {
    $searched = mysqli_query($connect, "SELECT * FROM people WHERE `description` LIKE '%$searcharray%'");
    while($info = mysqli_fetch_array($searched)) {
    echo $info['description'];
    }
}

因此,例如,用户输入'他是男性'。我把这个词分成了三个部分'他''是'和男性'使用'爆炸'功能。之后,我在数据库中搜索与这三个单词类似的单词。但是,如果一行包含所有三个单词,则会显示该行三次。如何让它只显示一次?

5 个答案:

答案 0 :(得分:2)

你可以这样做:

$search = 'test search me';
$search_split = array_map(function($piece) use ($mysqli_connection){
    return "'%" . $mysqli_connection->real_escape_string($piece) . "%'";
}, explode(' ', $search)); //$search is what user entered
$search_split = implode(' OR `description` LIKE ', $search_split);
$sql = "SELECT * FROM people WHERE `description` LIKE $search_split";
echo $sql; // SELECT * FROM people WHERE `description` LIKE '%test%' OR `description` LIKE '%search%' OR `description` LIKE '%me%'
$searched = mysqli_query($connect, $sql);

答案 1 :(得分:2)

您可以使用full text search吗?

向表格添加全文索引

ALTER TABLE people ADD FULLTEXT(description);

然后你可以使用像这样的查询

SELECT * 
FROM people 
WHERE 
MATCH ( description ) 
AGAINST ('+He +is +male' IN BOOLEAN MODE)

答案 2 :(得分:1)

首先将结果存储到一个数组中然后显示它。请参阅下面的代码。

$search_split = explode(" ", $search); //$search is what user entered
foreach ($search_split as $searcharray) {
    $searched = mysqli_query($connect, "SELECT * FROM people WHERE `description` LIKE '%$searcharray%'");
    while($info = mysqli_fetch_array($searched)) {
     $results[$info['YOUR_PRIMARY_KEY']] = $info['description']; // this will over write your previous record
    }
}
foreach($results as $result){
  echo $result;
}

现在每条记录只显示一次。

答案 3 :(得分:0)

您已将数据库查询放在foreach循环中,循环循环3次(使用当前数据:他,是和男性)。您要做的是将所有搜索变量放在一个查询中,例如:

$search_split = explode(" ", $search); //$search is what user entered
$querypart = "'%" . implode("%' AND '%", $search_split) . "%'"; // use OR or AND, to your liking

$searched = mysqli_query($connect, "SELECT * FROM people WHERE `description` LIKE " . $querypart);
while($info = mysqli_fetch_array($searched)) {
    echo $info['description'];
}

这不会对查询输入进行任何转义/清理,请注意......

答案 4 :(得分:0)

$result = array();    

$search_split = explode(" ", $search); //$search is what user entered
    foreach ($search_split as $searcharray) {
        $searched = mysqli_query($connect, "SELECT * FROM people WHERE `description` LIKE '%$searcharray%'");
        while($info = mysqli_fetch_array($searched)) {
            $result[] = $info['description'];
        }
    }

$finalres = array_unique($result);

所以,finalres包含独特的结果

for($i = 0; $i < count($finalres); $i++)
    echo $finalres[$i];