Home >Database >Mysql Tutorial >How to Order MySQL Fulltext Search Results by Relevance?

How to Order MySQL Fulltext Search Results by Relevance?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-05 07:21:02344browse

How to Order MySQL Fulltext Search Results by Relevance?

How to Rank MYSQL Fulltext Search Results by Relevance

Question:

How do I order MYSQL fulltext search results by relevance, prioritizing exact matches and sorting partial matches alphabetically?

Answer:

To perform a fulltext search in MYSQL, use the MATCH(...) AGAINST(...) construct instead of the LIKE operator. MATCH(...) AGAINST(...) returns a relevancy score for each result, which can be used to sort the results by relevance.

Here's a modified query that uses fulltext search and sorts the results by relevancy:

SELECT * FROM `vocabulary`
WHERE MATCH(`translation`) AGAINST ('word')
ORDER BY MATCH(`translation`) AGAINST ('word') DESC;

This query will return results with an exact match first, followed by partial matches sorted in descending order of relevance.

Example:

Consider the following vocabulary table:

id translation
1 word
2 crossword
3 words
4 wordsmith

Running the above query with the search term "word" would return the following results sorted by relevance:

id translation
1 word
2 crossword
3 words
4 wordsmith

The above is the detailed content of How to Order MySQL Fulltext Search Results by Relevance?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn