更好地订购mysql / php搜索结果

时间:2012-03-06 22:58:21

标签: php mysql

我有一个mysql / php查询,它搜索数据库并根据用户输入的搜索字符串返回匹配项,按标题升序排序,但我们真的希望按最佳匹配排序(类似于ElasticSearch用分数对搜索结果进行排名的方式)。

目前,在搜索“quake II”时,结果列表如下所示:

- Quake
- Quake 4
- Quake II
- Quake III Arena

预期结果列表必须是:

- Quake II (corresponding exactly to the search)
- Quake III Arena (containing entirely the search)
- Quake
- Quake 4

当前的php / mysql查询是:

$nameKeys = explode(" ", $gamenamethathasbeensearchedfor);
$query = "SELECT id FROM games WHERE GameTitle LIKE '%$nameKeys[0]%'";
for($i = 1; $i <= count($nameKeys); $i++)
{
    if($nameKeys[$i] != "" || $nameKeys[$i] != " " || $nameKeys[$i] != "  " || $nameKeys[$i] != "   ")
    {
        $query .= " AND GameTitle LIKE '%$nameKeys[$i]%'";
    }
}

1 个答案:

答案 0 :(得分:2)

我会在GameTitle上设置FullText索引,然后你可以利用MySQL的全文排序和排序的强大功能,而无需编写一些复杂的查询。也就是说,如果您没有使用InnoDB。你也可以这样做,

SELECT id, MATCH (GameTitle) AGAINST ('%$nameKeys[$i]%') AS SCORE FROM games WHERE MATCH (GameTitle) AGAINST ('%$nameKeys[$i]%') limit 10;

这可以让你非常接近,而不必修改索引,但我建议你查看MySQL Full-text functions