简体   繁体   English

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

[英]Better ordering of mysql/php search results

I have a mysql/php query which searches through a database and returns matches based on a search string that has been input by the user, it is sorted by title ascending, however we would really like it to be sorted by best match (similar to the way ElasticSearch ranks search results with a score). 我有一个mysql / php查询,它搜索数据库并根据用户输入的搜索字符串返回匹配,按标题升序排序,但我们真的希望按最佳匹配排序(类似于ElasticSearch对搜索结果进行排名的方式)。

Currently, when searching for "quake II" the result list looks like: 目前,在搜索“quake II”时,结果列表如下所示:

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

Expected result list must be: 预期结果列表必须是:

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

The current php/mysql query is: 目前的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]%'";
    }
}

I would set up a FullText index on GameTitle, then you can take advantage of the power of MySQL's full-text ordering and sorting without having to write some complex query. 我会在GameTitle上设置一个FullText索引,然后你可以利用MySQL的全文排序和排序的强大功能,而无需编写一些复杂的查询。 That is, if you are not using an InnoDB. 也就是说,如果您没有使用InnoDB。 You could do something like this as well, 你也可以这样做,

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

This should get you pretty close without having to modify your indexes but I would recommend checking out MySQL Full-text functions 这应该让你非常接近,而不必修改索引,但我建议检查MySQL全文功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM