简体   繁体   中英

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).

Currently, when searching for "quake II" the result list looks like:

- 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:

$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. That is, if you are not using an 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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