[MySQL] Understanding Full-Text Search in MySQL: Why MATCH() Appears Twice

Understanding Full-Text Search in MySQL: Why MATCH() Appears Twice

When implementing search functionality in a MySQL database using full-text search, it's common to encounter a query like this:
SELECT *, MATCH(title, aliases) AGAINST(%s) AS relevance
FROM 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.

HAVING is used instead of WHERE here because relevance is an alias of a computed column, not a direct column in the table.


Why Use MATCH() Twice?

  • The first MATCH() (in the WHERE clause) is used to filter rows.

  • The second MATCH() (in the SELECT clause) 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 sub
WHERE relevance > 5.0;

However, repeating MATCH() is a widely accepted and efficient pattern for basic search queries.

Comments