Search code examples
mysqlsqlstringmatchsql-like

Match mySQL with any word in string


SELECT * FROM Restaurants WHERE Name LIKE '%{$_GET["searchval"]}%'

The above code will return all entries in the Restaurants table where the name field contains the searchval.

For example, if the searchval was "Example Entry" and the database had an entry with the name "Example Entry Number Five", that entry would display. But, if the entry was "Example Number Five" it would not display.

How can I make it such that if the database entry contains any one word in the string, it will display. Such that "Example Entry" would display if the entry had "Example" or "Entry" in it.


Solution

  • The best solution are full text indexes. However, you can do what you want using regular expressions.

    Assuming that words are separated by only one word, you can do:

    where name rlike replace({$_GET["searchval"]}, ' ', '|')
    

    If you really want to take the regular expressions approach, I would suggest that you do the value parsing in the application layer. But, this does do what you want in the database, assuming that words are separated by a space and not using special regular expression characters.