Featured image of post MySQL Reverse Fuzzy Lookup

MySQL Reverse Fuzzy Lookup

You must have used MySQL's fuzzy search, but have you tried reverse fuzzy search?

When developing a WeChat auto-reply demo, I encountered this scenario:

  1. Receive specific messages
  2. Reply with predefined content based on keywords stored in database
  3. Requires partial matching with fuzzy database queries

For conventional fuzzy matching, everyone knows to use LIKE. Given this table structure:

id   keyword    reply
1     David      This is David
2     KingDavid  This is David

If the input keyword is “David”, we need to find all records containing David. The SQL would be:
SELECT * FROM table_name WHERE keyword LIKE '%David%'


Now consider a reverse scenario: We store only one record in the database that can match both “David” and “King David” with the same reply. This requires reverse fuzzy lookup. Table data:

id     keyword      reply
1      %David%      This is David

The corresponding reverse lookup SQL would be:
SELECT * FROM table_name WHERE 'David' LIKE keyword

This query pattern inverts the conventional fuzzy search logic - instead of matching database entries against user input, we match user input against predefined patterns in the database. The % wildcards in the database’s keyword field enable flexible partial matching from the user’s input perspective.