[MySQL] Understanding Full-Text Search in MySQL: Why MATCH() Appears Twice
Understanding Full-Text Search in MySQL: Why MATCH() Appears Twice
SELECT *, MATCH(title, aliases) AGAINST(%s) AS relevanceFROM game_table WHERE MATCH(title, aliases) AGAINST(%s IN NATURAL LANGUAGE MODE)HAVING relevance > 5.0;
At first glance, it may seem odd that the MATCH() function is used twice. But this is intentional and necessary.
What This Query Does
1. MATCH(title, aliases) AGAINST(...)
This uses MySQL's full-text search to evaluate how relevant the given keyword is to the title and aliases columns.
2. SELECT *, ... AS relevance
Returns all columns (*) and adds a computed column called relevance, which is the relevance score of the match.
3. WHERE MATCH(...) AGAINST(...)
Filters rows to include only those that match the search term using natural language mode.
4. HAVING relevance > 5.0
Further filters the result, returning only rows with a relevance score above 5.0.
HAVINGis used instead ofWHEREhere becauserelevanceis an alias of a computed column, not a direct column in the table.
Why Use MATCH() Twice?
-
The first
MATCH()(in theWHEREclause) is used to filter rows. -
The second
MATCH()(in theSELECTclause) is used to compute and return the relevance score.
Even though the logic looks identical, MySQL does not allow reusing the result of the MATCH() from the WHERE clause in the SELECT. That's why it must be called again.
Can This Be Avoided?
If avoiding repetition is a concern, it's possible to refactor the query using a subquery or Common Table Expression (CTE) (if supported):
SELECT *FROM ( SELECT *, MATCH(title, aliases) AGAINST(%s) AS relevance FROM game_table) AS subWHERE relevance > 5.0;
However, repeating MATCH() is a widely accepted and efficient pattern for basic search queries.
Comments
Post a Comment